What's the best way to tell if a Python program has anything to read from stdin?

前端 未结 4 646
一向
一向 2020-12-05 02:36

I want a program to do one thing if executed like this:

cat something | my_program.py

and do another thing if run like this



        
4条回答
  •  醉话见心
    2020-12-05 02:46

    If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal:

    $ python -c 'import sys; print sys.stdin.isatty()'
    True
    $ echo | python -c 'import sys; print sys.stdin.isatty()'
    False
    

提交回复
热议问题