import os.path
import re
import socket
host = ''
port = 6366
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.bind ((host, port))
def request ():
print ("What file should I write to?")
file = input ()
thing = os.path.exists (file)
if thing == True:
start = 0
elif file.endswith ('.txt'):
stuff = open (file, "w")
stuff.write ("Requests on what to add to the server. \n")
stuff.close ()
start = 0
else:
start = 1
go = "yes"
list1 = (start, file, go)
return list1
start = 1
while start == 1:
list1 = request ()
(start, file, go) = list1
def loop ():
print ("Listening for requests.")
s.listen (1)
conn, addr = s.accept ()
print ("Connected to {0}".format(addr))
while 1:
want = conn.recv(1024).decode()
if not want:
break
if want == "shutdown":
thingy = "no"
print ("Writing to {0}".format(file))
x = open (file, "a")
x.write (want + "\n")
x.close ()
print ("Done writing to {0}".format(file))
x = open (file, "a")
x.write (format(addr) + "\n")
x.close ()
print ("Disconnecting from {0}".format(addr))
conn.close()
print ("Disconnected from {0}".format(addr))
return thingy
while go == "yes":
go = loop ()
if go == "no":
print ("Shutting down")
这是一台服务器。每当我尝试回归" thingy"在第50行,我收到以下错误。
Traceback (most recent call last):
File "H:\Python\Server Requests\Listen.py", line 52, in <module>
go = loop ()
File "H:\Python\Server Requests\Listen.py", line 50, in loop
return thingy
UnboundLocalError: local variable 'thingy' referenced before assignment
我不明白为什么我会收到此错误。我没有在那个循环之外引用它。我有什么遗失的吗?
答案 0 :(得分:5)
对于那个错误;
def loop ():
print ("Listening for requests.")
thingy=""
s.listen (1)
conn, addr = s.accept ()
print ("Connected to {0}".format(addr))
只需在函数中添加一个名为 thingy 的空变量。它应该可以解决你的问题。
答案 1 :(得分:0)
尝试声明空变量,然后在满足条件时分配值。您的退货声明将有效。