2013-03-18 13 views
0

之前引用局部变量我有一段代码,这里在Python线程(服务器),但是当我运行客户端发现这些错误:“UnboundLocalError:局部变量‘一站式’分配之前引用” :的Python:UnboundLocalError:分配

import threading 
import msvcrt 

stop = False 
Buffer= 1024 

class ChatServer(threading.Thread): 
    def __init__(self,channel,addr,counter): 
     self.channel = channel 
     self.addr = addr 
     self.counter = counter 
     threading.Thread.__init__(self) 
     self.start() 

    def run(self): 
     # press s to trigger 
     if msvcrt.kbhit(): 
      if msvcrt.getch() == 's': 
       stop = True 
       print "Login is closed closed.\n" 
     while 1: 
      if (stop == False): 
       print "\nClient connection received!\n" 
       self.channel.send("Status: Server connection received") 

counter = 0     
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
server.bind(("",500)) 
server.listen(20) 

while True: 
    print "\nServer awaiting connections....\n" 
    channel, addr = server.accept() 
    counter += 1 
    ChatServer(channel,addr,counter) 
+3

一个重复的哦,所以许多[其他](https://www.google.com/search?q=stackoverflow+UnboundLocalError%3A+local+variable+referenced+before+assignment)... – shx2 2013-03-18 12:05:05

+0

可能重复的[UnboundLocalError:局部变量...在赋值之前引用](http://stackoverflow.com/questions/4048745/unboundlocalerror-local-variable-referenced-before-assignment) – 2013-03-18 15:27:48

回答

1

你只设置变量stop非常特殊的情况下,从来没有把它设置为False。将一个明确的stop = False添加到run()函数的顶部。

def run(self): 
    stop = False 
    # press s to trigger 
    if msvcrt.kbhit(): 
     if msvcrt.getch() == 's': 
      stop = True 
      print "Login is closed closed.\n" 
    while 1: 
     if (stop == False): 
      print "\nClient connection received!\n" 
      self.channel.send("Status: Server connection received") 

可能希望在某个时候设置stopwhile循环,因为它代表如果达到stop = True它永远不会停止。

+0

is stop = False是不够的,因为我声明它在顶部?如果我将stop = False添加到run()函数的顶部,那么stop永远不会有错误值? – Kit 2013-03-18 12:08:42

+0

@Kit:如果'msvcrt.kbhit()'为True并且'msvcrt.getch()'等于's'',那么'stop'设置为'True';你的'while 1'循环将会*永远不会*看到局部变量'stop'变成'False',因为循环内部没有任何内容会改变它的值。 – 2013-03-18 12:10:50

+0

@Wooble:谢谢你的修复,我不得不关注其他事情几分钟,并且格式化错误消失了。 – 2013-03-18 12:14:27