2013-03-06 102 views
3

以下代碼給出了全局名稱未定義的錯誤,但據我所知,名稱定義的。我是Python新手,這是範圍問題嗎?Python線程給出全局名稱未定義錯誤

import os, socket 
from threading import Thread 

class serv: 
    def __init__(self): 
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
     self.socket.bind(('', 443)) 

    def run(self): 
     self.socket.listen(10) 
     print "Listening" 
     self.conn, self.addr = self.socket.accept() 
     try: 
      Thread(target=clientThread, args=(self.conn,)).start() 
     except Exception, errtxt: 
      print errtxt 

    def exit(self): 
     print "Disconnected" 
     self.conn.close() 

    def clientThread(conn): 
     print "Connected" 
     while 1: 
      conn.send("Hello, worlds!\n") 

S = serv() 
S.run() 

特定的錯誤是

global name 'clientThread' is not defined 
+2

'pi'是一個概念loooooong在Raspberry Pi來到現場之前;請僅爲數學常量使用'pi'標籤。 :-) – 2013-03-06 21:02:27

+0

會這樣,謝謝。 – 2013-03-06 21:04:45

回答

6

你應該使用

self.clientThread 
+0

那麼修復了這個問題,現在更多!非常感謝。 – 2013-03-06 21:05:01

0

我會做這些改變:

(1)通selfself.clientThread

def run(self): 
    self.socket.listen(10) 
    print "Listening" 
    self.conn, self.addr = self.socket.accept() 
    try: 
     Thread(target=self.clientThread, args=(self,)).start() 
    except Exception, errtxt: 
     print errtxt 

(2)。參考selfclientThread

def clientThread(self): 
    print "Connected" 
    while 1: 
     self.conn.send("Hello, worlds!\n") 

另一種可能性是讓你從對象的threading.Thread代替具有螺紋派生。然後你的代碼看起來更像這樣:

import os, socket 
from threading import Thread 

class serv(Thread): 
    def __init__(self): 
     super(serv, self).__init__() 
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
     self.socket.bind(('', 443)) 

    def run(self): 
     self.socket.listen(10) 
     print "Listening" 
     self.conn, self.addr = self.socket.accept() 
     try: 
      print "Connected" 
      while 1: 
       self.conn.send("Hello, worlds!\n") 
     except Exception, errtxt: 
      print errtxt 

    def exit(self): 
     print "Disconnected" 
     self.conn.close() 

S = serv() 
S.start() 
相關問題