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

后端 未结 6 859
我在风中等你
我在风中等你 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
    闹比i (楼主)
    2021-02-01 20:56

    I'm a noob, so this might not be a good answer, but I'm trying to do the same thing (allow one or more files on the command line, default to STDIN otherwise).

    The final combo I put together:

    parser = argparse.ArgumentParser()
    parser.add_argument("infiles", nargs="*")
    args = parser.parse_args()
    
    for line in fileinput.input(args.infiles):
        process(line)
    

    This seems like the only way to get all the desired behavior in one elegant package, without requiring named args. Just like unix commands are used as such:

    cat file1 file2
    wc -l < file1
    

    Not:

    cat --file file1 --file file2
    

    Would appreciate feedback/confirmation from veteran idiomatic Pythonistas to make sure I've got the best answer. Haven't seen this complete solution mentioned anywhere else, just fragments.

提交回复
热议问题