Yes, it is very possible, I changed 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 you know, 0 is a file descriptor for input into the program. isatty is a test for checking a file descriptor that references the terminal or not. As another user pointed out, the above approach will determine if the program is reading the terminal or not. However, the goal of the question is solved over programming, but there is still room for improvement. We may have another solution that will simply determine if the program is reading from the channel 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")
source share