Argparse 可选位置参数?
我有一个应该这样使用的脚本:
usage: installer.py dir [-h] [-v]
dir
是一个位置参数,其定义如下:
parser.add_argument('dir', default=os.getcwd())
我希望 dir
是可选的:当未指定时它应该只是cwd
。
不幸的是,当我没有指定dir
参数时,我得到错误:参数太少
。
I have a script which is meant to be used like this:
usage: installer.py dir [-h] [-v]
dir
is a positional argument which is defined like this:
parser.add_argument('dir', default=os.getcwd())
I want the dir
to be optional: when it's not specified it should just be cwd
.
Unfortunately, when I don't specify the dir
argument, I get Error: Too few arguments
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
nargs='?'
(或nargs='*'
如果您需要多个目录)扩展示例:
Use
nargs='?'
(ornargs='*'
if you need more than one dir)extended example:
作为@VinaySajip 答案的扩展。 还有其他值得一提的
nargs
。parser.add_argument('dir', nargs=1, default=os.getcwd())
N(整数)。来自命令行的 N 个参数将被收集到一个列表
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'。所有存在的命令行参数都收集到一个列表中。 请注意,使用
nargs='*'
时使用多个位置参数通常没有多大意义,但使用nargs='* 时使用多个可选参数没有多大意义'
是可能的。parser.add_argument('dir', nargs='+', default=os.getcwd())
'+'。就像“*”一样,所有存在的命令行参数都被收集到一个列表中。此外,如果至少不存在一个命令行参数,则会生成一条错误消息。
parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())
argparse.REMAINDER
。所有剩余的命令行参数都收集到一个列表中。这对于分派到其他命令行实用程序的命令行实用程序通常很有用。如果未提供 nargs 关键字参数,则消耗的参数数量由操作确定。通常,这意味着将使用单个命令行参数并生成单个项目(不是列表)。
编辑(从@Acumenus的评论复制)
nargs='?'
文档 说:“?”。如果可能的话,将从命令行使用一个参数并将其作为单个项目生成。如果不存在命令行参数,则将生成默认值。As an extension to @VinaySajip answer. There are additional
nargs
worth mentioning.parser.add_argument('dir', nargs=1, default=os.getcwd())
N (an integer). N arguments from the command line will be gathered together into a list
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with
nargs='*'
, but multiple optional arguments withnargs='*'
is possible.parser.add_argument('dir', nargs='+', default=os.getcwd())
'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.
parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())
argparse.REMAINDER
. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilitiesIf the
nargs
keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.Edit (copied from a comment by @Acumenus)
nargs='?'
The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.简短回答
如前两个答案所示,您可以使用
nargs='?'
接受可选位置参数。如果您愿意,您还可以将参数直接转换为Path
类型和/或将 cwd 缩短为.
:myfile.py
更长的答案
由于您在问题中还提到了标志样式的 True/False 选项
-h
和-v
,因此这些示例可能有用:标志(例如
-v
)我们可能会将不带参数的可选选项称为“标志”。对于标志,我们只关心它们是否被给出。
-h
是 argparse 自动添加的标志(以及较长版本的--help
),因此我们不应该真正覆盖它。如果我们考虑-v
,则myfile.py
请注意,
add_argument()
的第二个参数是选项的较长名称。它不是强制性的,但它确实使您的后续代码更具可读性(parsed_args.version
与parsed_args.v
),并使对安装程序的调用更加明确。可选参数(例如
--installdir /usr/bin/
)有人可能会说,在您的情况下,您最好使用可选参数而不是位置参数。
myfile.py
Short Answer
As already shown in the previous two answers, you can accept an optional positional argument with
nargs='?'
. You could also turn the argument directly into aPath
type and/or shorten the cwd to.
if you wanted to:myfile.py
Longer answer
Since you also mention the flag-style True/False options
-h
and-v
in your question, these examples may be of use:Flags (e.g.
-v
)We might refer to optional options that take no arguments as "flags". With flags, we only care about whether they are given or not.
-h
is a flag that argparse adds automatically (along with the longer version--help
) so we shouldn't really override that. If we consider-v
then,myfile.py
Note that the second argument to
add_argument()
is a longer name for the option. It is not mandatory but it does make your subsequent code more readable (parsed_args.version
vsparsed_args.v
) and makes calls to your installer more explicit.Optional arguments (e.g.
--installdir /usr/bin/
)One could argue that, in your case, you would be better off with an optional argument rather than a positional one.
myfile.py
parser.add_argument
还有一个必需开关。您可以使用required=False
。以下是 Python 2.7 的示例片段:
parser.add_argument
also has a switch required. You can userequired=False
.Here is a sample snippet with Python 2.7: