6

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

1 Answer 1

5

If you use input redirection, the standard input is not connected to a terminal like it usually is. You can check if a file descriptor is connected to a terminal or not with the isatty function:

import os

def is_stdin_piped():
    return not os.isatty(0)

For extra safety use sys.stdin.fileno() instead of 0.

Update: To check if stdin is redirected from a file (rather than another program, such as an IDE or a shell pipeline) you can use fstat:

import os, stat

def is_stdin_a_file():
    status = os.fstat(0)
    return stat.S_ISREG(status.st_mode)
Sign up to request clarification or add additional context in comments.

2 Comments

It looks good and it does almost what I need. When I run it from the command line, everythin is working well. However, when I run it in PyDev IDE (therefore no piping) the is_stdin_piped() returns as it was piped. Any idea how to fix this? Thanks
Your IDE uses a pipe without you knowing it. But hold on - there's a way to check if the input is redirected from a file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.