Python Argparse 可选的位置参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4480075/
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
Argparse optional positional arguments?
提问by Waldo Bronchart
I have a script which is meant to be used like this:
usage: installer.py dir [-h] [-v]
我有一个脚本,打算这样使用:
usage: installer.py dir [-h] [-v]
diris a positional argument which is defined like this:
dir是一个位置参数,定义如下:
parser.add_argument('dir', default=os.getcwd())
I want the dirto be optional: when it's not specified it should just be cwd.
我希望dir是可选的:当它没有被指定时,它应该只是cwd.
Unfortunately when I don't specify the dirargument, I get Error: Too few arguments.
不幸的是,当我不指定dir参数时,我得到Error: Too few arguments.
采纳答案by Vinay Sajip
Use nargs='?'(or nargs='*'if you will need more than one dir)
使用nargs='?'(或者nargs='*'如果您需要多个目录)
parser.add_argument('dir', nargs='?', default=os.getcwd())
extended example:
扩展示例:
>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]
positional arguments:
dir
optional arguments:
-h, --help show this help message and exit
-v
回答by Matas Vaitkevicius
As an extension to @VinaySajip answer. There are additional nargsworth mentioning.
作为@VinaySajip 答案的扩展。还有其他nargs值得一提的。
parser.add_argument('dir', nargs=1, default=os.getcwd())
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
N(整数)。来自命令行的 N 个参数将被收集到一个列表中
parser.add_argument('dir', nargs='*', default=os.getcwd())
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'. All command-line arguments present are gathered into a list. Notethat it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*'is possible.
'*'。存在的所有命令行参数都被收集到一个列表中。请注意,具有多个位置参数 with 通常没有多大意义nargs='*',但多个可选参数 withnargs='*'是可能的。
parser.add_argument('dir', nargs='+', default=os.getcwd())
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())
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 utilities
argparse.REMAINDER. 所有剩余的命令行参数都收集到一个列表中。这对于分派到其他命令行实用程序的命令行实用程序通常很有用
If the nargskeyword 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.
如果nargs未提供关键字参数,则消耗的参数数量由操作决定。通常这意味着将使用单个命令行参数并生成单个项目(不是列表)。
Edit (copied from a comment by @Acumenus)nargs='?'The docssay: '?'. 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.
编辑(从@Acumenus 的评论中复制)nargs='?'文档说:“?”。如果可能,将从命令行使用一个参数并作为单个项目生成。如果不存在命令行参数,则将生成默认值。
回答by rakhee
parser.add_argumentalso has a switch required. You can use required=False.
Here is a sample snippet with Python 2.7:
parser.add_argument还需要一个开关。您可以使用required=False. 这是 Python 2.7 的示例片段:
parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

