使用argparse在Python中使用可选的stdin

[英]Optional stdin in Python with argparse


I found the very useful syntax

我发现了非常有用的语法

parser.add_argument('-i', '--input-file', type=argparse.FileType('r'), default='-')

for specifying an input file or using stdin—both of which I want in my program. However, the input file is not always required. If I'm not using -i or redirecting input with one of

用于指定输入文件或使用stdin - 我想在程序中使用它们。但是,并不总是需要输入文件。如果我没有使用-i或重定向输入

$ someprog | my_python_prog
$ my_python_prog < inputfile

I don't want my Python program to wait for input. I want it to just move along and use default values.

我不希望我的Python程序等待输入。我希望它只是移动并使用默认值。

2 个解决方案

#1


78  

The standard library documentation for argparse suggests this solution to allow optional input/output files:

argparse的标准库文档建议此解决方案允许可选的输入/输出文件:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
...                     default=sys.stdin)
>>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
...                     default=sys.stdout)
>>> parser.parse_args(['input.txt', 'output.txt'])
Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
          outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
>>> parser.parse_args([])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
          outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)

#2


18  

Use isatty to detect whether your program is in an interactive session or reading from a file:

使用isatty来检测您的程序是在交互式会话中还是从文件中读取:

if not sys.stdin.isatty(): # Not an interactive device.
  # ... read from stdin

However, for the sake of consistency and reproducability, consider following the norm and reading from stdin if the filename is -. You may want to consider to let the fileinput module handle that.

但是,为了保持一致性和可重复性,如果文件名为 - ,请考虑遵循规范并从stdin读取。您可能需要考虑让fileinput模块处理该问题。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/09/27/deacecaf8cddce1d752e9ef22a610e07.html



 
  © 2014-2022 ITdaan.com 联系我们: