2013-02-08 62 views
2

我的Python代碼中有一個錯誤,我是Python新手,而且我也是PyQT的新手。我想要做的是用GUI構建一個基本的http代理服務器。我已經在控制檯中完成了它,但是當我試圖實現GUI時,出現錯誤。當PyQT4與BaseHTTPServer混合時,Python會凍結

這是我的代碼,任何幫助表示讚賞。

import BaseHTTPServer, SocketServer,sys 
from PyQt4 import QtCore, QtGui 
from Ui_MiniGui import Ui_MainWindow 

class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): 
    pass 

class webServer(QtCore.QThread): 
    log = QtCore.pyqtSignal(object) 

    def __init__(self, parent = None): 
     QtCore.QThread.__init__(self, parent) 

    def run(self): 
     self.log.emit("Listening On Port 1805") 
     Handler = BaseHTTPServer.BaseHTTPRequestHandler 

     def do_METHOD(self): 
      method = self.command 
#I got some trouble here, how can i emit the signal back to the log? 
      #self.log.emit(method) not work, python not crash 
      #webServer.log.emit(method) not work, python not crash 
     #below one not work and python crashes immediately 
      webServer().log.emit(method) 

     Handler.do_GET = do_METHOD 

     self.httpd = ThreadingHTTPServer(("", 1805), Handler) 
     self.httpd.serve_forever() 

class Form(QtGui.QMainWindow): 
    def __init__(self, parent=None): 
     QtGui.QWidget.__init__(self, parent) 
     self.ui = Ui_MainWindow() 
     self.ui.setupUi(self) 
     self.server = webServer() 
     self.server.log.connect(self.write_to_textEdit) 
     self.server.start() 

    def write_to_textEdit(self, data): 
     print data 
     self.ui.textEdit.setText(data) 

if __name__ == "__main__": 

    app = QtGui.QApplication(sys.argv) 
    myapp = Form() 
    myapp.show() 
    sys.exit(app.exec_()) 

回答

1

在這一行

webServer().log.emit(method) 

您創建一個新的Web服務器實例,併發出它的日誌信號。由於這是一個新的對象,這個信號沒有連接到任何東西,所以它什麼都不做。

爲了發出正確的對象上的信號,你可以做到以下幾點:

def run(self): 
    ... 
    server = self 
    def do_METHOD(self): 
     ... 
     server.log.emit(self)