I am looking for a way how to determine whether stdin input comes from another application by piping or not.
Let say that I have a program that either accepts the input data from piped stdin (when you pipe it from another application - grep, tail, ...) or it uses a default data file. I don't want the user to fill in manually the data when prompted because there was no stdin piped.
My simple code example looks like this:
from sys import stdin
for line in stdin:
print line
When I run the script using this:
echo "data" | python example.py
I get
data
and the script ends.
While if I run the script in the following way,
python example.py
it prompts user to fill in the input and it waits.
Therefore I am looking for something like follows to avoid the prompt when no data are piped.
from sys import stdin
if is_stdin_piped():
for line in stdin:
print line
else:
print "default"
Is something like this possible? Thanks