Python: UnboundLocalError: local variable referenced before assignment
我在python线程(服务器)中有一段代码,但是当我运行客户机时,发现了这些错误:"unboundlocalerror:local variable'stop'referenced before assignment":
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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. " while 1: if (stop == False): print" Client connection received! " 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" Server awaiting connections.... " channel, addr = server.accept() counter += 1 ChatServer(channel,addr,counter) |
您只在非常特定的条件下设置变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def run(self): stop = False # press s to trigger if msvcrt.kbhit(): if msvcrt.getch() == 's': stop = True print"Login is closed closed. " while 1: if (stop == False): print" Client connection received! " self.channel.send("Status: Server connection received") |
您可能希望在某一点将