argparse 参数的可选值

argparse optional value for argument

我要区分这三种情况:

如何使用 Python argparse 执行此操作? action='store_true' 将涵盖前两种情况,但随后第三种情况将无效。

你可以用 nargs='?':

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. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced.

您的三个案例将得出:

  1. default值;
  2. const值;和
  3. '~/some/path'

分别。例如,给定以下简单实现:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('-t', nargs='?', default='not present', const='present without value')

print(parser.parse_args().t)

你会得到这个输出:

$ python test.py
not present

$ python test.py -t
present without value

$ python test.py -t 'passed a value'
passed a value