非阻塞键盘输入python

时间:2015-12-07 04:04:41

标签: python linux

当对等体持续监听传入连接(新对等体)并通过终端(用户输入)向其他对等体发送命令时,构建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检查来自新连接对等方的传入消息。我只需要一种发送消息的方式。

1 个答案:

答案 0 :(得分:1)

简短的回答是你需要使用curses

比调用input()并收到回复要困难得多,但这是你需要的。有一个名为Curses Programming with Python的好资源,这是最好的起点。