传递额外参数的Python argparse自定义操作 [英] Python argparse custom actions with additional arguments passed
本文介绍了传递额外参数的Python argparse自定义操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import argparse
class customAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
setattr(args, self.dest, values)
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--example', action=customAction)
我想在触发选项-e时将其他参数传递给customAction另一个类的实例。我怎样才能做到这一点?我尝试过的所有内容都出错了。
I want to pass additional arguments to customAction when the option -e is triggered, e.g. a instance of another class. How can I do this? Everything I have tried has errored out.
推荐答案
def make_action(additional_arg):
class customAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
print(additional_arg)
setattr(args, self.dest, values)
return customAction
#...
parser.add_argument('-e', '--example', action=make_action('your arg'))
这篇关于传递额外参数的Python argparse自定义操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文