argparse optional value for argument

早过忘川 提交于 2019-12-08 19:22:57

问题


I want to distinguish between these three cases:

  • The flag is not present at all python example.py;
  • The flag is present but without a value python example.py -t; and
  • The flag is present and has a value python example.py -t ~/some/path.

How can I do this with Python argparse? The first two cases would be covered by action='store_true' but then the third case becomes invalid.


回答1:


You can do this with 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.

Your three cases would give:

  1. The default value;
  2. The const value; and
  3. '~/some/path'

respectively. For example, given the following simple implementation:

from argparse import ArgumentParser

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

print(parser.parse_args().t)

You'd get this output:

$ python test.py
not present

$ python test.py -t
present without value

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


来源:https://stackoverflow.com/questions/30896982/argparse-optional-value-for-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!