我是Python的新手,非常习惯于C风格的编程,我在python中使用“if”语句时出错。我试图在while循环中增加一个变量;使用“if”语句在打印前先检查它,但由于某种原因它不起作用。这是下面的代码,我看到了类似的错误,但无法应用我从那里得到的
import socket
import time
import threading
tLock = threading.Lock()
shutdown = False
kt = 0
def receving(name, sock):
while not shutdown:
try:
tLock.acquire()
while True:
data, addr = sock.recvfrom(1024)
if kt > 0:
print str(kt)
kt = kt+1
except:
pass
finally:
tLock.release()
host = '127.0.0.1'
port = 0
server = ('127.0.0.1',5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
rT = threading.Thread(target=receving, args=("RecvThread",s))
rT.start()
alias = raw_input("Please Enter Your Name: ")
message = raw_input(alias + " Please Enter Your Password:")
while message != 'q':
if message != '':
s.sendto(alias + ":" + message, server)
tLock.acquire()
message = raw_input(alias + "-> ")
tLock.release()
time.sleep(0.2)
shudown = True
rT.join()
s.close()
这是服务器 导入套接字 进口时间 导入线程
host = '127.0.0.1'
port = 5000
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)
checkpass = False
quitting = False
print "Server Started."
while not quitting:
try:
data, addr = s.recvfrom(1024)
if checkpass == False:
userNa,passWo = data.split(":")
daata =[line.strip() for line in open("passFile.txt",'r')]
for index,item in enumerate(daata):
if userNa == daata[index] and passWo ==daata[index+1]:
checkpass = True
print "Welcome " + userNa +" You have successfully logged in!"
break;
else:
print "Your username and/or password was incorrect try again"
else:
print "well we tried"
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
print time.ctime(time.time()) + str(addr) + ": :" + str(data)
for client in clients:
s.sendto(data, client)
except:
pass
s.close()
答案 0 :(得分:0)
您的代码不应该运行。在函数receving
中,您应该获得UnboundLocalError
例外:
In [5]: kt = 0
In [6]: def test(s):
print('{} test'.format(s))
print('value of kt:', kt)
kt = kt + 1
...:
In [7]: test('first')
first test
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-7-0e641494ca48> in <module>()
----> 1 test('first')
<ipython-input-6-c37035372993> in test(s)
1 def test(s):
2 print('{} test'.format(s))
----> 3 print('value of kt:', kt)
4 kt = kt + 1
5
UnboundLocalError: local variable 'kt' referenced before assignment
您应该在函数中使用global
语句。
In [8]: def test2(s):
...: global kt
...: print('{} test'.format(s))
...: print('value of kt:', kt)
...: kt = kt + 1
...:
In [9]: test2('first')
first test
value of kt: 0
In [10]: test2('second')
second test
value of kt: 1
答案 1 :(得分:-1)
给出一个标签空间,除了,传递,最后,tLock.release()...尝试,除了应该在同一个缩进中..