Python read from command line arguments or stdin

拜拜、爱过 提交于 2020-01-02 01:54:26

问题


When writing text-oriented command line programs in Python, I often want to read either all the files passed on the command line, or (XOR) standard input (like Unix cat does, or Perl's <>). So, I say

if len(args) == 0:  # result from optparse
    input = sys.stdin
else:
    input = itertools.chain(*(open(a) for a in args))

Is this the Pythonic way of doing this, or did my miss some part of the library?


回答1:


You need fileinput.

A standard use case is:

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



回答2:


See

How do you read from stdin in Python?




回答3:


In Python 3, argparse handles filetype objects very nicely. It's an extremely powerful module and the docs come with many examples, so it's easy to quickly write the code you want. (How Pythonic!)

You may also benefit from this StackOverflow question about using argparse to optionally read from stdin.



来源:https://stackoverflow.com/questions/5675938/python-read-from-command-line-arguments-or-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!