2010-08-21

How to select stdin in Python Windows?

Views: 20965 | 1 Comment

The Python document says:

File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock.

In a recent project, I must continuously read from one network socket, forward to another socket, until the user input ‘q’ from the console. One may think to use threading, but I don’t want to deal with multi-thread stuffs. Finally, I found a none-clear solution, and it worked.

I create one thread – YES, thread, but no multi-thread concerns – this thread open a server socket listening on random port, then open a client socket connect to this server. The server socket accept the connection, then call sys.stdin.read() in a block way, all data read from stdin will write to that accepted connection. So client socket receive data reading from stdin. Now, the client socket is a *selectable* stdin, and it is thread-safe.

Download source code: stdio.py

Posted by ideawu at 2010-08-21 22:13:23 Tags: ,

One Response to "How to select stdin in Python Windows?"

  • Why do you say this script is for Windows?

    Neither sys.stdin.fileno nor os.read is supported on Windows. They can’t get you the expected result on Windows. Reply

Leave a Comment