如何在python argparse中使参数可选
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15754208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to make argument optional in python argparse
提问by user1416227
I would like to make these invocations of myprog work, and no others.
我想让这些对 myprog 的调用起作用,而没有其他调用。
$ python3 myprog.py -i infile -o outfile
$ python3 myprog.py -o outfile
$ python3 myprog.py -o
$ python3 myprog.py
In particular I want to make it illegal to specify the infile but not the outfile.
特别是我想让指定 infile 而不是 outfile 是非法的。
In the third case, a default name for the outfile is assumed, "out.json." In the second, third and fourth cases, a default name for the input file is assumed, "file.n.json", where n is an integer version number. In the fourth case the output file would be "file.n+1.json" where n+1 is a version number one larger than the one on the input file. The relevant section of my code is:
在第三种情况下,假定输出文件的默认名称为“out.json”。在第二种、第三种和第四种情况下,假定输入文件的默认名称为“file.n.json”,其中 n 是整数版本号。在第四种情况下,输出文件将是“file.n+1.json”,其中 n+1 是一个比输入文件大一的版本号。我的代码的相关部分是:
import argparse
parser = argparse.ArgumentParser(description="first python version")
parser.add_argument('-i', '--infile', nargs=1, type=argparse.FileType('r'), help='input file, in JSON format')
parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'), default='out.json', help='output file, in JSON format')
args = parser.parse_args()
print("Here's what we saw on the command line: ")
print("args.infile",args.infile)
print("args.outfile",args.outfile)
if args.infile and not args.outfile:
parser.error("dont specify an infile without specifying an outfile")
elif not args.infile:
print("fetching infile")
else: # neither was specified on the command line
print("fetching both infile and outfile")
Problem is, when I run
问题是,当我跑步时
$ python3 myprog.py -i infile.json
instead of the parser error I hoped for, I get:
而不是我希望的解析器错误,我得到:
Here's what we saw on the command line:
args.infile [<_io.TextIOWrapper name='infile.json' mode='r' encoding='UTF-8'>]
args.outfile <_io.TextIOWrapper name='out.json' mode='w' encoding='UTF-8'>
fetching both infile and outfile
...which suggests that even though there was no "-o" on the command line it acted as if there was.
...这表明即使命令行上没有“-o”,它也表现得好像有。
采纳答案by BenDundee
You specified a default argument for the outfile.
您为输出文件指定了默认参数。
parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'), default='out.json', help='output file, in JSON format')
If the -ooption isn't specified at the command line, the arg parser inserts the default argument.
如果-o在命令行中未指定该选项,则 arg 解析器将插入默认参数。
Change this to:
将此更改为:
parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'), help='output file, in JSON format')
and things should work as you expect.
事情应该像你期望的那样工作。
If you want to be able to specify -o, without a filename, you probably want something like:
如果您希望能够在-o没有文件名的情况下指定,您可能需要以下内容:
out_file = args.out if args.out is not None else 'json.out'
out_file = args.out if args.out is not None else 'json.out'
I'm not sure if the relevant parameter will be Noneor ''(i.e., empty string) if you specify the -owithout a parameter--I suspect it's None, but I don't know for sure. You'll have to test it out to be sure.
如果您指定不带参数的参数,我不确定相关参数是否为None或''(即空字符串)-o——我怀疑它是None,但我不确定。您必须对其进行测试才能确定。
I don't know how to do this without extra logic with argparse.
如果没有 argparse 的额外逻辑,我不知道如何做到这一点。
回答by mhristache
As an add-on to the selected answer:
作为所选答案的附加内容:
The option to run -owithout specifying a file, can be done using constcombined with nargs='?'.
可以在-o不指定文件的情况下运行的选项,可以const与nargs='?'.
From the docs:
从文档:
When add_argument() is called with option strings (like -f or --foo) and nargs='?'. This creates an optional argument that can be followed by zero or one command-line arguments. When parsing the command line, if the option string is encountered with no command-line argument following it, the value of const will be assumed instead. See the nargs description for examples.
当使用选项字符串(如 -f 或 --foo)和 nargs='?' 调用 add_argument() 时。这将创建一个可选参数,其后可以跟零个或一个命令行参数。解析命令行时,如果遇到选项字符串后面没有命令行参数,则将假定为 const 的值。有关示例,请参阅 nargs 描述。

