non blocking keyboard input python

家住魔仙堡 提交于 2021-02-20 04:37:05

问题


Im building a p2p system when the peers are constantly listening for incoming connections (new peers) and sending commands through the terminal (user input) to the other peers. I am having difficulty looking for user input from the keyboard while always looking for new peers.

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 checks for incoming messages from the newly connected peer. I just need a way of sending messages.


回答1:


The short answer is you'll need to use curses.

Its a lot more difficult than just calling input() and receiving a response, but it is what you'll need. There is a good resource called Curses Programming with Python which is the best place to start.



来源:https://stackoverflow.com/questions/34126256/non-blocking-keyboard-input-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!