Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for a python script to "know" if it is being piped to?

Tags:

python

pipe

myscript.py

import sys
if something_to_read_from_stdin_aka_piped_to:
    cmd = sys.stdin.read()
    print(cmd)
else:
    print("standard behavior")

Bash example:

echo "test" | python myscript.py

If it is not being piped to, it would hang.

What is the way to know if the script should or should not read from stdin; I'm hoping there's something obvious other than a command line argument for the script.

like image 370
PascalVKooten Avatar asked Feb 06 '16 23:02

PascalVKooten


1 Answers

Yes it is very much possible, I have modified your example to achieve this.

import sys
import os
if not os.isatty(0):
    cmd = sys.stdin.read()
    print(cmd)
else:
    print("standard behavior")

As we know 0 is file descriptor for input to program. isatty is test to check file descriptor refer to terminal or not. As pointed out by other user above approach will tell whether program is reading from terminal or not. However above programming solves the purpose of question but still there is room to improve. We can have another solution which will just detect if program is reading from pipe or not.

import sys
import os
from stat import S_ISFIFO

if S_ISFIFO(os.fstat(0).st_mode):
    print("Reading from pipe")
    cmd = sys.stdin.read()
    print(cmd)
else:
    print("not reading from pipe")
like image 198
AlokThakur Avatar answered Oct 29 '22 10:10

AlokThakur