An Intro to argparse

Have you ever wondered how to process command line arguments in Python? Yeah, there’s a module for that. It’s called argparse, which is a replacement for optparse. In this article, we’ll be taking a whirlwind tour of this helpful module. Let’s start with something simple!

Getting Started

I have always found the simplest way to explain a coding concept is to show some code. So that’s what we’re going to do. Here’s a super simple example that doesn’t do much of anything:

>>> import argparse
>>> parser = argparse.ArgumentParser(
...         description="A simple argument parser",
...         epilog="This is where you might put example usage"
...     )
... 
>>> parser.print_help()
usage: _sandbox.py [-h]

A simple argument parser

optional arguments:
  -h, --help  show this help message and exit

This is where you might put example usage

Here we just import argparse and give it a description and set up a usage section. The idea here is that when you ask the program you are creating for help, it will tell you how to use it. In this case, it prints out a simple description, the default optional arguments (“-h” in this case) and example usage.

Now let’s make this example a bit more concrete. You won’t normally be parsing arguments from the command-line after all. So we’ll move the code into a Python function inside of a Python file:

# arg_demo.py

import argparse

#----------------------------------------------------------------------
def get_args():
    """"""
    parser = argparse.ArgumentParser(
        description="A simple argument parser",
        epilog="This is where you might put example usage"
    )
    return parser.parse_args()

if __name__ == '__main__':
    get_args()

Now let’s call the script from the command line:

python arg_demo.py -h

This will print out the help text like we saw earlier. Now let’s learn about how to add some of our own custom arguments.


Adding Arguments

Let’s write some code that adds three new arguments that our parser can understand. We’ll add an argument that is required and two that are not. We’ll also look at adding a default and a required type. Here’s the code:

# arg_demo2.py

import argparse

#----------------------------------------------------------------------
def get_args():
    """"""
    parser = argparse.ArgumentParser(
        description="A simple argument parser",
        epilog="This is where you might put example usage"
    )

    # required argument
    parser.add_argument('-x', action="store", required=True,
                        help='Help text for option X')
    # optional arguments
    parser.add_argument('-y', help='Help text for option Y', default=False)
    parser.add_argument('-z', help='Help text for option Z', type=int)
    print(parser.parse_args())
    
if __name__ == '__main__':
    get_args()

Now let’s run it a few times so you can see what happens:

mike@pc:~/py/argsparsing$ python arg_demo2.py 
usage: arg_demo2.py [-h] -x X [-y Y] [-z Z]
arg_demo2.py: error: argument -x is required

mike@pc:~/py/argsparsing$ python arg_demo2.py -x something
Namespace(x='something', y=False, z=None)

mike@pc:~/py/argsparsing$ python arg_demo2.py -x something -y text
Namespace(x='something', y='text', z=None)

mike@pc:~/py/argsparsing$ python arg_demo2.py -x something -z text
usage: arg_demo2.py [-h] -x X [-y Y] [-z Z]
arg_demo2.py: error: argument -z: invalid int value: 'text'

mike@pc:~/py/argsparsing$ python arg_demo2.py -x something -z 10
Namespace(x='something', y=False, z=10)

As you can see, if you run the code without passing it any arguments, you will get an error. Next we pass it just the required argument so you can see what the defaults are for the other two. Then we try passing “text” to the ‘-y’ argument and that gets stored, so we know it doesn’t require a Boolean. The last two examples show what happens when you pass an invalid and a valid value to the ‘-z’ argument.

By the way, the argument names do not have to be one character in length. You can change those something more descriptive, like ‘arg1` or ‘simulator’ or whatever you want.


Wrapping Up

You now know how to create the basics of an argument parser. There are many other aspects of this module that you might be interested in, such as defining an alternate destination name for the argument to be saved to, using different prefixes (i.e. ‘+’ instead of ‘-‘), creating argument groups and more. I recommend checking out the documentation (linked below) for more details.


Additional Reading

2 thoughts on “An Intro to argparse”

  1. Pingback: Gooey GUI for Python Scripts – Python Marketer

  2. Pingback: 蠎周刊 2015 年度最赞 - 算法网

Comments are closed.