prattom
prattom

Reputation: 1753

stopping execution of code in clean way python

I have a GUI created using PyQt. In the GUI their is a button which when pressed send some data to client. Following is my code

class Main(QtGui.QTabWidget, Ui_TabWidget):
    def __init__(self):
        QtGui.QTabWidget.__init__(self)
        self.setupUi(self)
        self.pushButton_8.clicked.connect(self.updateActual)

    def updateActual():
        self.label_34.setText(self.comboBox_4.currentText())        
        HOST = '127.0.0.1'    # The remote host
        PORT = 8000              # The same port as used by the server
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.connect((displayBoard[str(self.comboBox_4.currentText())], PORT))
        except socket.error as e:
            err1 = str(self.comboBox_4.currentText()) + " is OFF-LINE"
            reply2 = QtGui.QMessageBox.critical(self, 'Error', err1, QtGui.QMessageBox.Ok)
            if reply2 == QtGui.QMessageBox.Ok:
                pass   #stop execution at this point
        fileName = str(self.comboBox_4.currentText()) + '.txt'
        f = open(fileName)
        readLines = f.readlines()
        line1 = int(readLines[0])
        f.close()

Currently if a user clicks 'ok' in QMessageBox the program will continue code execution in case their is socket exception. Thus my question is how can I stop the execution of code after 'except' in a clean way such that my UI doesn't crash and user can continue using it?

Upvotes: 0

Views: 448

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122142

Yes, you can simply return from the if block:

if reply2 == QtGui.QMessageBox.Ok:
    return

Alternatively, move your code for when it doesn't raise socket.error into an else block:

try: # this might fail
    s.connect(...)
except socket.error as e: # what to do if it fails
    err1 = ...
    reply2 = QtGui.QMessageBox.critical(...)
else: # what to do if it doesn't
    with open(fileName) as f:
        line1 = int(f.readline().strip())

Note that:

  1. You don't actually need to deal with the return from the message box, as it could only be OK and you have no else option;
  2. you should generally use with for file handling, it will automatically close at the end of the block; and
  3. you can simplify your file handling code by only reading the first line.

Upvotes: 1

Related Questions