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

后端 未结 6 873
我在风中等你
我在风中等你 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条回答
  •  -上瘾入骨i
    2021-02-01 20:48

    There is no reliable way to detect if sys.stdin is connected to anything, nor is it appropriate do so (e.g., the user wants to paste the data in). Detect the presence of a filename as an argument, and use stdin if none is found.

提交回复
热议问题