【问题标题】:Only one command line argument with argparse只有一个带有 argparse 的命令行参数
【发布时间】:2017-11-02 19:57:06
【问题描述】:

我正在尝试使用 argparse 以只接受一个或一次的方式实现一个命令行参数。多次出现应该被拒绝。

我使用下面的代码

#!/usr/bin/env python3
import argparse
cmd_parser = argparse.ArgumentParser()
cmd_parser.add_argument('-o', dest='outfile')
cmd_line = cmd_parser.parse_args()
print(cmd_line.outfile)

一个参数给出了预期的结果:

./test.py -o file1
file1

当两次发出参数时,第一次出现被静默忽略:

./test.py -o file1 -o file2
file2

我也尝试了nargs=1action='store',但没有达到预期的结果。

如何告诉 argparse 拒绝多个参数出现?

【问题讨论】:

标签: python argparse


【解决方案1】:

可以用自定义动作来安排:

import argparse

class Once(argparse.Action):
    def __init__(self, *args, **kwargs):
        super(Once, self).__init__(*args, **kwargs)
        self._count = 0

    def __call__(self, parser, namespace, values, option_string=None):
        # print('{n} {v} {o}'.format(n=namespace, v=values, o=option_string))
        if self._count != 0:
            msg = '{o} can only be specified once'.format(o=option_string)
            raise argparse.ArgumentError(None, msg)
        self._count = 1
        setattr(namespace, self.dest, values)

cmd_parser = argparse.ArgumentParser()
cmd_parser.add_argument('-o', dest='outfile', action=Once, default='/tmp/out')
cmd_line = cmd_parser.parse_args()
print(cmd_line.outfile)

您可以指定默认值:

% script.py 
/tmp/out

您可以指定一次-o

% script.py -o file1 
file1

但是指定-o 两次会引发错误:

% script.py -o file1 -o file2
usage: script.py [-h] [-o OUTFILE]
script.py: error: -o can only be specified once

【讨论】:

  • 谢谢 - 按预期工作。我在 argparse 中寻找解决方案,这就是为什么我忽略了自定义 Action 方法。
  • 我会在检查中添加默认值if getattr(namespace, self.dest) is not None and self.default is None:,因为如果您指定默认值,它将失败,而不是因为参数重复。
  • @lasote:我认为使用该条件将允许多次指定 -o 而不会引发错误,因为如果您指定非无默认值,self.default 将不会是 None .我已经更改了上面的代码,以以不同的方式适应上面的默认值。
猜你喜欢
  • 2011-09-17
  • 2020-05-04
  • 2018-10-14
  • 2012-01-05
  • 2018-08-11
  • 2021-09-24
  • 2013-06-08
  • 2013-08-19
相关资源
最近更新 更多