PYTHON:能够从同一个class级中调用一种方法的必要条件是什么?

我觉得我错过了这个代码工作的一个主要部分,或者真的很奇怪。 我已经包含了一个名为“handle”的方法,它被作为parameter passing给了thread.start_new_thread,但是这个方法似乎并没有被识别/执行。 即使在PythonWin编辑器中,当您键入“self”时。 它通常会预先填充一个可以识别的选项列表,并且句柄在这个版本中没有显示出来,但是在这个文件的工作版本中,它在编辑器中显示出来了。

这里是代码:

(大量import到这里)

class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "flaspsrv" _svc_display_name_ = "Flash Policy Server" _svc_description_ = "Initialize Flash Policy Server" def __init__(self,args): logging.basicConfig(filename='C:\\Uploads\\testing.log', level=logging.DEBUG, filemode='a', format='%(asctime)s %(levelname)s %(message)s') win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): try: self.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) except AttributeError: # AttributeError catches Python built without IPv6 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: # socket.error catches OS with IPv6 disabled self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) logging.info('Listening on port 843') self.sock.bind(('localhost', 843)) self.sock.listen(5) try: while True: thread.start_new_thread(self.handle, self.sock.accept()) except socket.error, e: logging.info('Error accepting connection: %s' % (e[1],)) def handle(self, conn, addr): logging.info('Temp2') addrstr = '%s:%s' % (addr[0],addr[1]) try: logging.info('Connection from %s' % (addrstr,)) with contextlib.closing(conn): # It's possible that we won't get the entire request in # a single recv, but very unlikely. request = conn.recv(1024).strip() if request != '<policy-file-request/>\0': logging.info('Unrecognized request from %s: %s' % (addrstr, request)) return logging.info('Valid request received from %s' % (addrstr,)) fo = file('flashpolicy.xml', 'rb') conn.sendall(fo.read(10001)) logging.info('Sent policy file to %s' % (addrstr,)) except socket.error, e: logging.info('Error handling connection from %s: %s' % (addrstr, e[1])) except Exception, e: logging.info('Error handling connection from %s: %s' % (addrstr, e[1])) if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) 

改变线

 thread.start_new_thread(self.handle, self.sock.accept()) 

 thread.start_new_thread(self.handle, *self.sock.accept()) 

从socket.accept()的文档中,这个套接字方法返回一个元组(conn, address) ,你的处理程序接受三个参数(包括对self的引用)。

thread.start_new_thread的第二个和第三个参数是args (位置参数)和kwargs (关键字参数),它们应该被传递给在线程模块中注册的回调函数。 所以除非你从socket.accept()解压参数,否则你可能会收到Type Error

所以你需要从self.socket解压缩返回的元组,然后作为参数处理。