python - 非阻塞键盘输入

标签 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 检查来自新连接的对等方的传入消息。我只需要一种发送消息的方式。

最佳答案

简短的回答是您需要使用 curses .

这比调用 input() 并接收响应要困难得多,但它正是您所需要的。有一个很好的资源叫做 Curses Programming with Python这是最好的起点。

关于python - 非阻塞键盘输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34126256/

相关文章:

python - python中的c类型和类型有区别吗?

嵌套列表的 Python 类型注释

python - 如何制作通用的 Python 应用程序

python - 如何在 python 中从全局范围运行 "exec"

c - 在哪里可以找到 eventfd_write 文档?

c - 如何在循环中连续打印变量并在 linux 下的 C 中按一下转义键终止?

Python 网络爬行抛出连接错误

c - Linux中errno和返回码的区别

linux - 我如何开始制作我自己的简单的基于 UNIX 的网络扫描仪?

linux - 在 Debian 上使用 Synology Cloud Station