使用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 联系我们: