带有 argparse 的 Python 中的可选标准输入 [英] Optional stdin in Python with argparse

查看:26
本文介绍了带有 argparse 的 Python 中的可选标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了非常有用的语法

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

用于指定输入文件或使用标准输入——这两者都是我在我的程序中想要的.但是,并不总是需要输入文件.如果我不使用 -i 或使用其中之一重定向输入

$ someprog |my_python_prog$ my_python_prog <输入文件

我不希望我的 Python 程序等待输入.我希望它继续前进并使用默认值.

解决方案

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

<预><代码>>>>解析器 = argparse.ArgumentParser()>>>parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),...默认= sys.stdin)>>>parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),...默认=sys.stdout)>>>parser.parse_args(['input.txt', 'output.txt'])命名空间(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)>>>parser.parse_args([])命名空间(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,outfile=<_io.TextIOWrapper name='<stdout>'编码='UTF-8'>)

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

$ 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.

解决方案

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

>>> 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'>)

这篇关于带有 argparse 的 Python 中的可选标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆