我正在用Python编写一个聊天程序,需要在接受来自sys.stdin的用户输入之前连接到服务器。如果无法建立连接,则程序退出。
I'm writing a chat program in Python that needs to connect to a server before user input from sys.stdin is accepted. If a connection cannot be made then the program exits.
从shell运行此命令,如果连接失败并且在尝试连接时发送了输入,则输入将回显到程序退出后的shell:
Running this from the shell, if a connection fails and input was sent while attempting to connect, the input is echoed to the shell after the program exits:
jtink@gab-dec:~$ python chat.py attempting to connect... Hey there! # This is user input How are you? # This is more user input connection failed jtink@gab-dec:~$ Hey there! Hey there!: command not found jtink@gab-dev:~$ How are you? How are you?: command not found jtink@gab-dev:~$有没有办法判断sys.stdin上是否还有输入,以便我可以在聊天程序退出之前读取它?
Is there a way to tell if there is input left on sys.stdin, so that I can read it before the chat program exits?
我已阅读这个类似的问题,但答案只描述如何判断输入是否通过管道输入到python程序,而不是如何判断是否有输入。
I have read this similar question, but the answers only describe how to tell if input is being piped to a python program, not how to tell if there is input.
推荐答案我认为你需要检查这个关于stdin 上的非阻塞I / O的问题在subprocess.PIPE上的非阻塞读取在python中
I think that you need to check this SO question about non-blocking I/O on stdin Non-blocking read on a subprocess.PIPE in python
更多推荐
如何判断Python程序是否有从stdin读取的内容?
发布评论