[英]Python argparse: both optional and positional value for an argument
Consider the following usage: 请考虑以下用法:
usage: do.py [-h] [-s | -m] filename
This is not the complete usage. 这不是完整的用法。 But I effectively want is
filename
to be an actual value of file and not: 但我实际上希望
filename
是filename
的实际值,而不是:
--filename FILENAME
But also, filename
should be optional so I can read from the standard input. 但是,
filename
应该是可选的,以便我可以从标准输入中读取。 Think about the cat
program on UNIX. 考虑一下UNIX上的
cat
程序。
You simply say: 您只是说:
cat filename
OR 要么
cat
EDIT: Right now, if I execute the program do.py
without any command line options, I will get an error: too few arguments
. 编辑:现在,如果我在没有任何命令行选项的情况下执行程序
do.py
,我将得到一个error: too few arguments
。 Instead I would still want it to execute even if I don't give it a valid filename
. 相反,即使我没有给它一个有效的
filename
我仍然希望它执行。 How do I do that? 我怎么做?
Update 2: From the ArgParse documentation, 更新2:从ArgParse文档中,
One of the more common uses of nargs='?'
nargs ='?'的较常见用法之一 is to allow optional input and 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=<open file 'input.txt', mode 'r' at 0x...>, outfile=<open file 'output.txt', mode 'w' at 0x...>) >>> parser.parse_args([]) Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>, outfile=<open file '<stdout>', mode 'w' at 0x...>)
Original answer: 原始答案:
This is straightforward: just add a positional argument with a default value and a nargs='*'
. 这很简单:只需添加一个带有默认值和
nargs='*'
的位置参数nargs='*'
。 The default value will be used if there are zero arguments, otherwise the arguments on the command line will be used: 如果参数为零,将使用默认值,否则将使用命令行上的参数:
>>> p = argparse.ArgumentParser()
>>> p.add_argument('filename', nargs='*', default=['-'])
>>> p.parse_args([])
Namespace(filename=['-'])
>>> p.parse_args(['abc'])
Namespace(filename=['abc'])
Typically, -
is used to refer to standard input / standard output. 通常,
-
用于表示标准输入/标准输出。
Then you do something like this: 然后,您可以执行以下操作:
def get_inputs(ns):
"""Iterate over input files."""
for path in ns.filename:
if path == '-':
yield sys.stdin
else:
yield open(path, 'r')
Update: I assumed you wanted multiple filenames, since cat
takes multiple filenames. 更新:我假设您想要多个文件名,因为
cat
需要多个文件名。 You can use nargs='?'
您可以使用
nargs='?'
if you want either zero or one filename. 如果要使用零或一个文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.