1
$ script.py status
$ script.py terminate
$ script.py tail /tmp/some.log

As you can see the script can perform 3 tasks. The last task requires an additional argument (path of the file).

I want to use add_argument only once like below.

parser.add_argument("command")

And then check what command was requested by user and create conditionals based upon the same. If the command is tail I need to access the next argument (file path)

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133

1 Answers1

1

You might have to create a sub-parser for each command. This way it is extendable if those other commands also need arguments at some point. Something like this:

import argparse

parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--foo', action='store_true', help='global optional argument')
subparsers = parser.add_subparsers(dest="command", help='sub-command help')

# create the parser for the "status" command
parser_status = subparsers.add_parser('status', help='status help')

# create the parser for the "tail" command
parser_tail = subparsers.add_parser('tail', help='tail help')
parser_tail.add_argument('path', help='path to log')

print parser.parse_args()

The dest keyword of the add_subparsers ensures that you can still get the command name afterwards, as explained here and in the documentation.

Example usage:

$ python script.py status   
Namespace(command='status', foo=False)

$ python script.py tail /tmp/some.log
Namespace(command='tail', foo=False, path='/tmp/some.log')

Note that any global argument needs to come before the command:

$ python script.py tail /tmp/some.log --foo
usage: PROG [-h] [--foo] {status,tail} ...
PROG: error: unrecognized arguments: --foo

$ python script.py --foo tail /tmp/some.log
Namespace(command='tail', foo=True, path='/tmp/some.log')
Graipher
  • 6,891
  • 27
  • 47