Python: UnboundLocalError:引用前未赋值的局部变量
我这里有一段用Python写的线程代码(服务器),但是当我运行客户端时,出现了一个错误:“UnboundLocalError: 在赋值之前引用了局部变量'stop'”。
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)
1 个回答
1
你只在非常特定的情况下设置了变量 stop
,而且从来没有把它设置为 False
。在 run()
函数的开头加上一个明确的 stop = False
。
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")
你 可能 想在 while
循环的某个时刻设置 stop
,因为现在的情况是,如果达到了 stop = True
,程序将永远不会停止。