【问题标题】:stopping execution of code in clean way python以干净的方式停止执行代码python
【发布时间】:2014-01-27 15:41:06
【问题描述】:

我有一个使用 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 中单击“确定”,程序将继续执行代码,以防出现套接字异常。因此,我的问题是如何以干净的方式停止执行“除外”之后的代码,以使我的 UI 不会崩溃并且用户可以继续使用它?

【问题讨论】:

  • 我可以只写空返回'return'而不​​是'pass'

标签: python-2.7 pyqt


【解决方案1】:

是的,您可以在 if 块中简单地 return:

if reply2 == QtGui.QMessageBox.Ok:
    return

或者,将您的代码移到raise socket.error 块中:

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. 您实际上不需要处理从消息框返回的问题,因为它只能是 OK 而您没有else 选项;
  2. 一般应该使用with进行文件处理,它会在块的末尾自动close;和
  3. 您可以通过仅阅读第一行来简化文件处理代码。

【讨论】:

  • 感谢您告诉我有关“与”的信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 2021-11-04
  • 2021-03-12
  • 1970-01-01
相关资源
最近更新 更多