How to read from stdin or from a file if no data is piped in Python?

后端 未结 6 862
我在风中等你
我在风中等你 2021-02-01 20:19

I have a CLI script and want it to read data from a file. It should be able to read it in two ways :

  • cat data.txt | ./my_script.py
  • ./my
6条回答
  •  粉色の甜心
    2021-02-01 20:53

    You can use this function to detect if the input is from a pipeline or not.

    sys.stdin.isatty()
    

    It returns false if the input is from pipeline or true otherwise.

提交回复
热议问题