简体   繁体   English

Python argparse-具有'store_true'行为的用户定义操作

[英]Python argparse - user defined Action with 'store_true' behavoiur

Hi I suppose that i have parser argument which cannot pass any value, for example: 嗨,我想我有无法传递任何值的解析器参数,例如:

parser.add_argument('-s', '--staged', action=FooAction)

And my user defined action: 而我的用户定义动作:

class FooAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")

When i trying call this without any values: 当我尝试不带任何值调用此方法时:

python my_script -s

I receive this error message: 我收到此错误消息:

test.py: error: argument -s/--staged: expected one argument

I know that i can add action 'store_true' to my argument, but in this solution i cannot redirect execution of this argument to my defined action class. 我知道我可以将操作'store_true'添加到我的参数中,但是在这种解决方案中,我无法将此参数的执行重定向到我定义的操作类中。

Is someone know how to modify FooAction to achieve 'store_true" action behaviour? 有人知道如何修改FooAction来实现'store_true'行为吗?

edit 编辑

class Fooaction with set nargs=0: 设置nargs = 0的Fooaction类:

class FooAction(argparse.Action):
    def __init__(self, option_strings, dest, nargs=0, **kwargs):
        super(FooAction, self).__init__(option_strings, dest, nargs, **kwargs)
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")
import argparse

class FooAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")
        print(self)
        print(parser, namespace, values, option_string)

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--staged', action=FooAction, nargs=0)
args = parser.parse_args()
print(args)

sample run: 样品运行:

1151:~/mypy$ python3 stack56348020.py -s
action
FooAction(option_strings=['-s', '--staged'], dest='staged', nargs=0, const=None, default=None, type=None, choices=None, help=None, metavar=None)
ArgumentParser(prog='stack56348020.py', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True) Namespace(staged=None) [] -s
Namespace(staged=None)

Using your init 使用你的init

import argparse

class FooAction(argparse.Action):
    def __init__(self, option_strings, dest, nargs=0, **kwargs):
        super(FooAction, self).__init__(option_strings, dest, nargs=nargs, **kwargs)
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")
        print(parser, namespace, values, option_string)

parser = argparse.ArgumentParser()
a1 = parser.add_argument('-s', '--staged', action=FooAction)
print(a1)   # display the action object and most of its parameters
args = parser.parse_args()
print(args)

1208:~/mypy$ python3 stack56348020.py -s
FooAction(option_strings=['-s', '--staged'], dest='staged', nargs=0, const=None, default=None, type=None, choices=None, help=None, metavar=None)
action
ArgumentParser(prog='stack56348020.py', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True) Namespace(staged=None) [] -s
Namespace(staged=None)

add_argument returns the Action object it created. add_argument返回它创建的Action对象。 We usually ignore, it saving it to a reference, and print it can be handy during debugging. 我们通常会忽略它,将其保存到参考中,并在调试过程中方便打印。

Even though the Action subclasses are marked as 'private' (with _ ) it's a good idea to look at their code to see how they customize the base class. 即使Action子类被标记为“ private”(带有_ ),查看它们的代码以查看如何自定义基类也是一个好主意。 Action class by itself doesn't do much. Action类本身并不能做什么。 The default action uses _StoreAction . 默认操作使用_StoreAction Store True/False subclass _StoreConst . 存储True / False子类_StoreConst _HelpAction is the only one that does not store some sort of value in the namespace ; _HelpAction是唯一不在namespace存储某种值的函数; and it does a system exit. 并退出系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM