Is there a way for a python script to “know” if it is connected to a channel?

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 connected to the network, it will hang.

What is the way to know if a script should read or read text from stdin; I hope there is something obvious besides the command line argument for the script.

+6
source share
1 answer

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") 
+7
source

All Articles