argparse参数的可选值 [英] argparse optional value for argument

查看:96
本文介绍了argparse参数的可选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想区分这三种情况:

  • 该标志根本不存在python example.py;
  • 该标志存在,但没有值python example.py -t;和
  • 该标志存在并且值为python example.py -t ~/some/path.
  • 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.

如何使用Python argparse做到这一点?前两个案例将由action='store_true'覆盖,但随后第三个案例将变为无效.

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.

推荐答案

您可以使用

You can do this with nargs='?':

如果可能,将从命令行使用一个参数,并且 作为单个项目生产.如果不存在命令行参数,则 将产生默认值.请注意,对于可选参数, 还有另外一种情况-选项字符串存在但不存在 然后是命令行参数.在这种情况下,const的值 将产生.

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

您将获得以下输出:

$ python test.py
not present

$ python test.py -t
present without value

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

这篇关于argparse参数的可选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆