[EDIT: This series has been renamed so as not to conflict with Doug Hellman’s excellent Python Module of the Week series. See UPMotW #1 for details]
I’m going to try something different today. This is going to be the first in a series (hopefully once weekly) of Python Modules of the Week. This has probably been done to death elsewhere, but I’m using it as an opportunity to learn some more Python and to cement some of these modules in my mind.
Argparse is a Python module for processing command line arguments. It’s new in version 2.7 and is designed to replace the Optparse module. I’m not sure what the rationale for the change was as the two modules look very similar to me. However, it suffices to say that you should use argparse in all new code.
The main class of argparse is called ArgumentParser, it allows you to add arguments to your program and parse the provided arguments at runtime:
parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose") # a flag type argument parser.add_argument("value", type=int) # an integer positional argument ... args = parser.parse_args() # parse the args from sys.argv print(args.value) # arguments accessed as data members
You can also add meta-data such as help and descriptions to your arguments via keyword arguments to many of the methods. Take a look at the module documentation for examples. Once nice thing is that when you provide this data, argparse automatically generates the -h and –help flags and populates them with nicely formatted help output using the info you provide.
The argument parsing provided by argparse allows you to create some very complex command line interfaces to your scripts. I especially like the sub-commands framework, which allows each sub-command to exist as its own separate entity with its own options and help information. To create an argument parser with a sub-command is just a few lines:
parser = argparse.ArgumentParser() subcommands = parser.add_subparsers() mysubcommand = subcommands.add_parser('mysubcommand')
Of course,each sub-command is an ArgumentParser in its own right, so you can add all the options that you normally would, including command line flags, positional arguments and help information. Also each sub-command will be listed in the help and will also have its own help page which can be accessed via:
./pyprog.py subcommand --help
All in all, this is a very useful Python module to know about. Its ease of use and the number of things it ‘just takes care of’ make it a pleasure to use. Hopefully it’ll have you writing nice command line interfaces to all those hacked together scripts that are currently controlled by commenting bits of them in and out!