开发者

How can you tell if a Python program has anything to read from 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.

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 foun开发者_运维知识库d
jtink@gab-dev:~$

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?

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.


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


There are two general solutions to this problem:

  • When exiting because you couldn't connect to the server, read any remaining input from stdin and discard it. This solves your immediate problem today but only addresses one situation.

  • (Better) Set up a real event loop so that the connection to the server happens "in the background", which means your program is still reading from stdin at the same time it's trying to connect. You will want to use this solution if you need to say, reconnect to the server if the connection drops for some reason.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜