1

My goal is to have

  • myScript init without more run the class/action InitAction.
  • myScript foo /tmp run the class/action FooAction using the given "/tmp"

With argparse I made up this parser

parser = argparse.ArgumentParser(description="Look like GIT!")

parserCommands = parser.add_subparsers(title="Actions")

init_parser = parserCommands.add_argument('init', help='Set up')
destroy_parser = parserCommands.add_parser('destroy', help='Tear down')

Good till here but I want to bind init to the InitAction(argparse.Action). Something that works like action=InitAction but unfortunately this isn't allowed there.

Do you have a clue how to run InitAction when writing myScript.py init in the terminal?

1 Answer 1

2

The argparse documentation has an example of calling functions based on the subparser command

16.4.5.1. Sub-commands

One particularly effective way of handling sub-commands is to combine the use of the add_subparsers() method with calls to set_defaults() so that each subparser knows which Python function it should execute. For example:

>>> # create the parser for the "foo" command
>>> parser_foo = subparsers.add_parser('foo')
>>> ...
>>> parser_foo.set_defaults(func=foo)
...
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('foo 1 -x 2'.split())
>>> args.func(args)

Following that is an example using the 'dest':

the dest keyword argument to the add_subparsers() call will work'

I don't think you want to subclass argparse.Action. Normally an Action puts a value in the args namespace. The 'init' string is actually a value that subparsers Action uses to pass control to the init_parser. That's why your own Action class does not fit. What you want is function that can be run after parse_args is done, and all it needs to use is args.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.