python if run in terminal 1

python if run in terminal

import sys
if sys.stdin.isatty():
    # running interactively
    print "running interactively"
else:
    with open('output','w') as f:
        f.write("running in the background!\n")

Here is what the above code is Doing:
1. sys.stdin.isatty() returns True if the input is coming from a terminal, and False if it’s coming from a pipe or a file.
2. If the input is coming from a terminal, we print a message and exit.
3. If the input is coming from a pipe or a file, we write a message to a file.

Similar Posts