python - argparse 模块如何在没有任何参数的情况下添加选项?

标签 python argparse

我使用 argparse 创建了一个脚本。

脚本需要一个配置文件名作为选项,用户可以指定是完全执行脚本还是只模拟它。

要传递的参数:./script -f config_file -s./script -f config_file.

-f config_file 部分没问题,但它一直要求我提供 -s 的参数,该参数是可选的,不应跟随任何参数。

我试过这个:

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file')
#parser.add_argument('-s', '--simulate', nargs = '0')
args = parser.parse_args()
if args.file:
    config_file = args.file
if args.set_in_prod:
        simulate = True
else:
    pass

出现以下错误:

File "/usr/local/lib/python2.6/dist-packages/argparse.py", line 2169, in _get_nargs_pattern
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
TypeError: can't multiply sequence by non-int of type 'str'

'' 而不是 0 相同的错误。

最佳答案

作为 @Felix Kling suggested使用 action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

关于python - argparse 模块如何在没有任何参数的情况下添加选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5262702/

相关文章:

python - 复杂结构上的 pycparser.plyparser.ParseError

python - 在 Pandas 中移动窗口以检查特定范围值

Python 参数解析 : metavar and action=store_true together

python argparse 带有可检测开关的可选位置参数

python - 使用 argparse 完成 Bash 选项卡不显示目录中的所有文件

python:从 ScalarMappable 获取整个 numpy 数组的颜色

python - 概率与机器学习

python - 使用python脚本ssh连接到路由器

python - 在 Python 中使用 argparse 为具有两个值的参数设置单独的选择

python - 强制 argparse 将所有内容作为一个输入