argparse argumen的可选值

2024-04-26 00:07:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想区分这三种情况:

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

如何使用Python argparse实现这一点?前两种情况将由action='store_true'覆盖,但第三种情况则无效。在


Tags: pathstorepytrueexample标志argparse情况
1条回答
网友
1楼 · 发布于 2024-04-26 00:07:03

您可以使用^{}执行此操作:

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)

你会得到这样的输出:

^{pr2}$

相关问题 更多 >