Argparse可选的位置参数?

问题:Argparse可选的位置参数?

我有一个打算像这样使用的脚本: usage: installer.py dir [-h] [-v]

dir 是一个位置参数,其定义如下:

parser.add_argument('dir', default=os.getcwd())

我希望dir可以是可选的:未指定时,它应该只是cwd

不幸的是,当我不指定dir参数时,我得到了Error: Too few arguments

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.


回答 0

使用nargs='?'(或nargs='*' 如果您需要多个目录)

parser.add_argument('dir', nargs='?', default=os.getcwd())

扩展示例:

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

Use nargs='?' (or nargs='*' if you will need more than one dir)

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

回答 1

作为@VinaySajip答案的扩展。还有其他nargs值得一提的

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N(整数)。命令行中的N个参数将一起收集到一个列表中

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

‘*’。存在的所有命令行参数都收集到一个列表中。请注意,使用多个位置参数通常没有多大意义nargs='*',但可以使用多个可选参数nargs='*'

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

‘+’。就像’*’一样,所有存在的命令行参数都被收集到一个列表中。此外,如果没有至少一个命令行参数,则会生成一条错误消息。

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

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

  1. 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 with nargs='*' is possible.

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

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

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


回答 2

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

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with 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()