Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to tell if a Python program has anything to read from stdin?

Tags:

python

People also ask

What is difference between stdin and input in Python?

Stdin stands for standard input which is a stream from which the program reads its input data. This method is slightly different from the input() method as it also reads the escape character entered by the user. More this method also provides the parameter for the size i.e. how many characters it can read at a time.

What does stdin mean in Python?

When you run your Python program, sys. stdin is the file object connected to standard input (STDIN), sys. stdout is the file object for standard output (STDOUT), and sys. stderr is the file object for standard error (STDERR).


If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal:

$ python -c 'import sys; print sys.stdin.isatty()'
True
$ echo | python -c 'import sys; print sys.stdin.isatty()'
False

You want the select module (man select on unix) It will allow you to test if there is anything readable on stdin. Note that select won't work on Window with file objects. But from your pipe-laden question I'm assuming you're on a unix based os :)

http://docs.python.org/library/select.html

root::2832 jobs:0 [~] # cat stdin_test.py
#!/usr/bin/env python
import sys
import select

r, w, x = select.select([sys.stdin], [], [], 0)
if r:
    print "READABLES:", r
else:
    print "no pipe"

root::2832 jobs:0 [~] # ./stdin_test.py
no pipe

root::2832 jobs:0 [~] # echo "foo" | ./stdin_test.py
READABLES: [<open file '<stdin>', mode 'r' at 0xb7d79020>]

Bad news. From a Unix command-line perspective those two invocations of your program are identical.

Unix can't easily distinguish them. What you're asking for isn't really sensible, and you need to think of another way of using your program.

In the case where it's not in a pipeline, what's it supposed to read if it doesn't read stdin?

Is it supposed to launch a GUI? If so, you might want to have a "-i" (--interactive) option to indicate you want a GUI, not reading of stdin.

You can, sometimes, distinguish pipes from the console because the console device is "/dev/tty", but this is not portable.