gpt4 book ai didi

python - argparse 参数的可选值

转载 作者:太空狗 更新时间:2023-10-29 21:42:45 25 4
gpt4 key购买 nike

我想区分这三种情况:

  • 标志根本不存在 python example.py;
  • 标志存在但没有值 python example.py -t;和
  • 标志存在并具有值 python example.py -t ~/some/path

如何使用 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. 默认值;
  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

关于python - argparse 参数的可选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30896982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com