cmd = sys.stdin.read()
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.
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")