当对等点不断监听传入连接(新对等点)并通过终端(用户输入)向其他对等点发送命令时,我正在构建一个 p2p 系统。在寻找新同伴时,我很难从键盘寻找用户输入。
print 'Listening...'
while not shutdown:
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]: #look for keyboard input... not working
line = sys.stdin.readline()
if line:
send_message(line)
else: # an empty line means stdin has been closed
print('eof')
exit(0)
try: # listen for other peers
clientsock,clientaddr = mySocket.accept()
print 'Incoming connection from', clientaddr
clientsock.settimeout(None)
t = threading.Thread( target = HandlePeer, args = [clientsock] )
t.start()
except KeyboardInterrupt:
print "shutting down"
shutdown = True
continue
except Exception,e:
print 'error in peer connection %s %s' % (Exception,e)
mySocket.close()
HandlePeer 检查来自新连接的对等方的传入消息。我只需要一种发送消息的方式。
最佳答案
简短的回答是您需要使用 curses .
这比调用 input()
并接收响应要困难得多,但它正是您所需要的。有一个很好的资源叫做 Curses Programming with Python这是最好的起点。
关于python - 非阻塞键盘输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34126256/