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

后端 未结 6 868
我在风中等你
我在风中等你 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:47

    Process your non-filename arguments however you'd like, so you wind up with an array of non-option arguments, then pass that array as the parameter to fileinput.input():

    import fileinput
    for line in fileinput.input(remaining_args):
        process(line)
    

提交回复
热议问题