相关疑难解决方法(0)

在argparse中禁用/删除参数

是否可以删除或禁用argparse中的参数,以便它不会显示在帮助中?怎么样?

添加新参数很容易:

parser = argparse.ArgumentParser()
parser.add_argument('--arg1', help='Argument 1')
parser.add_argument('--arg2', help='A second one')
Run Code Online (Sandbox Code Playgroud)

我知道你可以通过指定"resolve"冲突处理程序来覆盖带有新定义的参数:

#In one script that should stand-alone and include arg1:

parser = argparse.ArgumentParser(conflict_handler='resolve')
parser.add_argument('--arg1', help='Argument 1')
parser.add_argument('--arg2', help='A second one')

#In another script with similar options
parser.add_argument('--arg1', help='New number 1')
Run Code Online (Sandbox Code Playgroud)

但这仍然包括帮助消息中的arg1和结果parse_args是否有类似的东西

#Wishful thinking
#In another script with similar options, that shouldn't include arg1
parser.remove_argument('--arg1')
Run Code Online (Sandbox Code Playgroud)

或者另一种合理简单的方法来实现这一目标?

另外:如果论证是位置论证,那么方法会不同吗?

注:排除故障arg1解析的建议后,这里是参数仍显示在帮助

python arguments argparse

17
推荐指数
4
解决办法
1万
查看次数

argparse - 组合父解析器,子解析器和默认值

我想在脚本中定义不同的子分析器,同时继承来自公共父级的选项,但具有不同的默认值.但它没有按预期工作.

这是我做的:

import argparse

# this is the top level parser
parser = argparse.ArgumentParser(description='bla bla')

# this serves as a parent parser
base_parser = argparse.ArgumentParser(add_help=False)
base_parser.add_argument('-n', help='number', type=int)


# subparsers
subparsers = parser.add_subparsers()
subparser1= subparsers.add_parser('a', help='subparser 1', 
                                   parents=[base_parser])
subparser1.set_defaults(n=50)
subparser2 = subparsers.add_parser('b', help='subparser 2',
                                   parents=[base_parser])
subparser2.set_defaults(n=20)

args = parser.parse_args()
print args
Run Code Online (Sandbox Code Playgroud)

当我从命令行运行脚本时,这就是我得到的:

$ python subparse.py b
Namespace(n=20)

$ python subparse.py a
Namespace(n=20)
Run Code Online (Sandbox Code Playgroud)

显然,第二个会set_defaults覆盖父母中的第一个.由于argparse文档中没有任何关于它的内容(非常详细),我认为这可能是一个错误.

有一些简单的解决方案吗?之后我可以检查args变量并将None值替换为每个subparser的预期默认值,但这正是我期望argparse为我做的.

顺便说一下,这是Python 2.7.

python argparse

12
推荐指数
2
解决办法
6455
查看次数

Custom conflict handling for ArgumentParser

What I need

I need an ArgumentParser, with a conflict handling scheme, that resolves some registered set of duplicate arguments, but raises on all other arguments.

What I tried

My initial approach (see also the code example at the bottom) was to subclass ArgumentParser, add a _handle_conflict_custom method, and then instantiate the subclass with ArgumentParser(conflict_handler='custom'), thinking that the _get_handler method would pick it up.

The Problem

This raises an error, because the ArgumentParser inherits from _ActionsContainer, …

python subclass argparse

7
推荐指数
1
解决办法
766
查看次数

标签 统计

argparse ×3

python ×3

arguments ×1

subclass ×1