2014-01-09 43 views
0

我有一個使用PyQt創建的GUI。在GUI中,它們是一個按鈕,當按下時發送一些數據給客戶端。以下是我的代碼以乾淨的方式停止執行代碼python

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

目前,如果用戶點擊「OK」在QMessageBox提示程序將繼續的情況下,代碼執行的是插座例外。因此,我的問題是,如何以乾淨的方式停止「except」之後的代碼執行,以便我的UI不會崩潰並且用戶可以繼續使用它?

+0

我可以寫簡單的空回報'return'而不​​是'pass' – prattom

回答

1

是的,你可以簡單地returnif塊:

if reply2 == QtGui.QMessageBox.Ok: 
    return 

或者,將你的代碼的時候它不raise socket.errorelse塊:

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. 您實際上不需要處理返回n從消息框中,因爲它只能是好的,你沒有else選項;
  2. 您一般應該使用with進行文件處理,它會在塊的結尾處自動生成close;和
  3. 你可以通過只讀第一行來簡化你的文件處理代碼。
+0

感謝您告訴我有關'with'的信息。 – prattom