3

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 found
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.

Community
  • 1
  • 1
Sadly Not
  • 234
  • 2
  • 15

2 Answers2

3

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

Community
  • 1
  • 1
Michael Dillon
  • 31,973
  • 6
  • 70
  • 106
3

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • In both of those solutions if there is no input then I will be waiting to read nothing ... which is something I want to avoid. The whole 'read any remaining input from stdin' is basically my question. – Sadly Not Feb 08 '11 at 18:15
  • Be sure not to use blocking reads on either stdin or your network socket. – Greg Hewgill Feb 08 '11 at 18:17