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

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

    Argparse allows this to be done in a fairly easy manner, and you really should be using it instead of optparse unless you have compatibility issues.

    The code would go something like this:

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', type = argparse.FileType('r'), default = '-')
    

    Now you have a parser that will parse your command line arguments, use a file if it sees one, or use standard input if it doesn't.

提交回复
热议问题