1

Some programs hang if they are executed by themselves on the command line such that they are supposed to be receiving input from standard input (i.e., sed "s/test/text/g"). How can a Python script determine if it is being passed data from standard input so an appropriate an error can be raised to avoid hanging for such input?

Melab
  • 2,594
  • 7
  • 30
  • 51

1 Answers1

1

How about:

import sys
if sys.__stdin__.isatty():
     print('Interactive')
else
     print('Non-Interactive')

Which produces the following output:

C:\>python bobo.py
Interactive

C:\>echo "test" | python bobo.py
Non-Interactive

See also os.isatty()

theB
  • 6,450
  • 1
  • 28
  • 38