Python 2.7 以干净的方式停止代码的执行
我有一个使用PyQt创建的GUI。在GUI中有一个按钮,按下该按钮时,会向客户端发送一些数据。下面是我的代码Python 2.7 以干净的方式停止代码的执行,python-2.7,pyqt,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)
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不会崩溃,用户可以继续使用它?是的,您只需从
if
块返回:
if reply2 == QtGui.QMessageBox.Ok:
return
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())
或者,当您的代码未提升套接字时,将其移动到块中。错误
:
if reply2 == QtGui.QMessageBox.Ok:
return
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())
请注意:
实际上,您不需要处理来自消息框的返回,因为它只能是OK,并且您没有else
选项李>
您通常应使用和
进行文件处理,它将在块末尾自动关闭
;及
我可以写简单的空返回“return”而不是“pass”谢谢你告诉我关于“with”。