gpt4 book ai didi

python - argparse 中的自定义 'usage' 函数?

转载 作者:太空狗 更新时间:2023-10-29 17:06:39 25 4
gpt4 key购买 nike

是否可以添加自定义“用法”函数而不是 python argparse 提供的默认用法消息。

示例代码:

parser = argparse.ArgumentParser(description='Sample argparse py')
parser.add_argument('-arg_1',type=int, custom_usage_funct('with_some_message'))
output = parser.parse_args()

def custom_usage_funct(str):
print str
print '''
Usage: program.py
[-a, Pass argument a]
[-b, Pass argument b]
[-c, Pass argument c]
[-d, Pass argument d]
comment
more comment
'''

如果传递的参数是一个字符串值而不是整数,那么程序应该调用一个带有错误消息“请提供一个整数值”的自定义函数

有效参数

program.py -arg_1 123

无效参数

program.py -arg_1 abc

Please provide an integer value
Usage: program.py
[-a, Pass argument a]
[-b, Pass argument b]
[-c, Pass argument c]
[-d, Pass argument d]
comment
more comment

最佳答案

是的,可以使用 usage= 关键字参数覆盖默认消息,如下所示,

def msg(name=None):                                                            
return '''program.py
[-a, Pass argument a]
[-b, Pass argument b]
[-c, Pass argument c]
[-d, Pass argument d]
comment
more comment
'''

和使用

import argparse
parser = argparse.ArgumentParser(description='Sample argparse py', usage=msg())
parser.add_argument("-arg_1", help='with_some_message')
parser.print_help()

上面的输出是这样的,

usage: program.py
[-a, Pass argument a]
[-b, Pass argument b]
[-c, Pass argument c]
[-d, Pass argument d]
comment
more comment


Sample argparse py

optional arguments:
-h, --help show this help message and exit
-arg_1 ARG_1 with_some_message

注:引用here

您还可以根据参数输入调用自定义函数 using action= 关键字参数:

>>> class FooAction(argparse.Action):
... def __call__(self, parser, namespace, values, option_string=None):
... print '%r %r %r' % (namespace, values, option_string)
... setattr(namespace, self.dest, values)
...
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=FooAction)
>>> parser.add_argument('bar', action=FooAction)
>>> args = parser.parse_args('1 --foo 2'.split())
Namespace(bar=None, foo=None) '1' None
Namespace(bar='1', foo=None) '2' '--foo'
>>> args
Namespace(bar='1', foo='2')

关于python - argparse 中的自定义 'usage' 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21185526/

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