我在python 2.7.10下遇到一个奇怪的问题,这是我的代码的相关部分:
...
#is called whenever the reinitscore() is called, and if the if statement is correct
def calculateWinner(d):
scores = {}
high_score = 0
for key, value in d.items():
try:
scores[value].append(key)
except KeyError:
scores[value] = [key]
if value > high_score:
high_score = value
results = scores[high_score]
if len(results) == 1:
print results[0]
stelnet.send(results[0])
return results[0]
else:
print 'TIE'
return 'TIE', results
#is called once, then every 5 seconds automatically with threading
def reinitScore():
threading.Timer(5, reinitScore).start()
global leftKeyCounter
global rightKeyCounter
global frontKeyCounter
global backKeyCounter
values = {'left' : leftKeyCounter, 'right' : rightKeyCounter, 'front' : frontKeyCounter, 'back' : backKeyCounter}
if (leftKeyCounter != 0 or rightKeyCounter != 0 or frontKeyCounter != 0 or backKeyCounter != 0):
calculateWinner(values)
leftKeyCounter = 0
rightKeyCounter = 0
frontKeyCounter = 0
backKeyCounter = 0
print "back to 0"
else:
stelnet.send("test")
if __name__ == "__main__":
if(len(sys.argv) < 3):
print 'Usage : python telnet.py hostname port'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
stelnet = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
stelnet.settimeout(2)
# connect to remote host
try:
stelnet.connect((host, port))
except:
print 'Unable to connect'
sys.exit()
...
while 1:
socket_list = [sys.stdin, stelnet]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == stelnet:
data = sock.recv(4096)
if not data:
print 'Connection closed'
sys.exit()
else:
#print data
sys.stdout.write(data)
#user entered a message
else:
msg = sys.stdin.readline()
stelnet.send(msg)
所以这里发生了什么:calculateWinner()由reinitScore调用,并通过telnet连接发送结果。在calculateWinner()函数中发送telnet没有问题,但是当我想在reinitScore()中使用stelnet.send()时,他返回这个
很奇怪,我可以在函数中使用stelnet.send,彼此相邻,而不是在另一个函数中......
另外,我的python一直在给我
这非常烦人,因为我只使用制表符而不是任何空格,他甚至强迫我使用unindent部分(请参阅reinitScore()的结尾)以接受运行代码......
我正在使用Sublime Text(由于众所周知的&#34; sublime&#34;隐藏字符的问题,但不会改变任何东西)改为Brackets ...