Adding options which both change behaviour and store an argument
Using the argparse
module, is it possible to perform multiple actions for a given argument?
Specifically, I'd like to provide a -l
/--list
option with nargs='?'
that will change the behaviour of the program from its main function to one of giving information about all possibilities in a 开发者_高级运维set or about one particular possibility.
Normally there will be a namespace attribute that contains a function to be called after parsing; I would like the -l
option to both change this attribute and optionally store its argument in a different attribute.
Is this possible?
Simply implement your own Action
subclass. This basically looks like this:
class ListAction(argparse.Action):
def __call__(parser, namespace, values, option_string=None):
setattr(namespace, 'list', values[0])
do_something_completely_different()
The argparse documentation has more details.
精彩评论