以干净的方式停止执行代码python

时间:2014-01-09 07:39:47

标签: python-2.7 pyqt

我有一个使用PyQt创建的GUI。在GUI中,它们是一个按钮,按下时会向客户端发送一些数据。以下是我的代码

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()

目前,如果用户在QMessageBox中单击“确定”,程序将继续执行代码,以防它们是套接字异常。因此,我的问题是如何以一种干净的方式停止'except'之后的代码执行,这样我的UI不会崩溃,用户可以继续使用它?

1 个答案:

答案 0 :(得分:1)

是的,您只需return阻止if

if reply2 == QtGui.QMessageBox.Ok:
    return

或者,将代码移至raise socket.error块时移至else块:

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())

请注意:

  1. 您实际上不需要处理来自消息框的返回,因为它只能是正常而您没有else选项;
  2. 您通常应该使用with进行文件处理,它会在块的末尾自动close;和
  3. 只需阅读第一行即可简化文件处理代码。