Python argparse

Filed Under: Python

Python argparse module is the preferred way to parse command line arguments. Parsing command-line arguments is a very common task, which Python scripts do and behave according to the passed values.

Python argparse

Python argparse is the recommended command-line argument parsing module in Python. It is very common to the getopt module but that is a little complicated and usually need more code for the same task.

Let us go through various ways in which we can parse command-line arguments using this module.

Why we need Python argparse module?

We will try to establish our need for argparse module by looking at a simple example of using sys module:


import sys

if len(sys.argv) > 1:
    print("Argument 1: {}".format(sys.argv[0]))
    print("Argument 2: {}".format(sys.argv[1]))
else:
    print("No arguments passed.")

With no arguments passed, the output will be:
python command line arguments

Clearly, even the script name is caught a command-line parameter as well because, well, that’s what it is for python.

Python argparse example

Now, you must be thinking that the above example was simple in terms of getting the arguments and using them. But thing is, when the script needs the parameters and they are not passed to it, that’s when the problems start.

With argparse, we can gracefully handle the absence and presence of parameters. Let’s study a simple example:


import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

Let’s run the script various times with different options to see what it leads to:
python argparse example

Let’s understand what happened when we ran the script:

  • Firstly, we ran the program with no arguments. In this case, the script remained silent.
  • The --help option is the only option which we need not specify with argparse as optional or required.
  • In last case, we used an unknown option which argparse,
    claimed as unrecognized arguments.

So, with argparse, we can define which arguments to expect and which are optional.

Python argparse positional arguments

Now, in our scripts, it will be often when we need an argument which is mandatorily be passed to the script on execution. We will see an error if not passed. Let’s see an example:


import argparse

parser = argparse.ArgumentParser()
parser.add_argument("blog")
args = parser.parse_args()

if args.blog == 'JournalDev':
    print('You made it!')
else:
    print("Didn't make it!")

When we run the script with different parameters, none, correct and something else:
python argparse positional arguments

So, this way we can show an error when the argument is not passed and manage different values as well when it is passed.

Python argparse positional arguments default values

In our last example, positional argument value is empty when not provided. But sometimes we want default values of a variable or argument, we can do that with argparse module.

See an example on how to pass default value for an argument:


import argparse

parser = argparse.ArgumentParser()
parser.add_argument('blog', nargs='?', default="JournalDev")
args = parser.parse_args()

if args.blog == 'JournalDev':
    print('You made it!')
else:
    print("Didn't make it!")

When we run the script with different parameters, none, correct and something else:
python argparse positional argument default values

This time, absence of a parameter was gracefully managed as default values were passed.

Python argparse argument help

Whenever we make a new Python script, we know what arguments to pass and what is the fate of each argument. But what about a user who knows nothing about our script? How does he know what arguments to pass, in which order and what they do?

This is where another attribute in add_argument function comes to the rescue:


import argparse

parser = argparse.ArgumentParser()
parser.add_argument('blog', default="JournalDev", help="Best blog name here.")
args = parser.parse_args()

if args.blog == 'JournalDev':
    print('You made it!')
else:
    print("Didn't make it!")

Now, when we run our script as (-h is for help):


python argparse_positional_help.py -h

We get the following output:
python argparse module positional argument help option

Isn’t that good? This way, the user of the script just needs to see what he/she should pass and in what order. Excellent!

Positional arguments Data Type

Now, Positional arguments are always treated as Strings, unless you tell Python not to. Let’s see this with a sample code snippet:


import argparse

parser = argparse.ArgumentParser()
parser.add_argument('number', help="Enter number to triple it.")
args = parser.parse_args()
print(args.number*3)

In this script, we are just multiplying a number with three. When we run this with 3 as the input, we get the following output:
python argparse argument data type

That happended because Python treated 3 as a String, so it just appended the same String 3 time.

This can be corrected if we inform Python of the datatype as with the help of type attribute:


import argparse

parser = argparse.ArgumentParser()
parser.add_argument('number', help="Enter number to cube.", type=int)
args = parser.parse_args()
print(args.number*3)

This time when we run this script with 3 as the input, we get the following output:
python argument parse example

This way, we can even ensure that the passed data types are correct.

Python argparse optional arguments

Now, in our scripts, it will be often when we need an argument which is optional be passed to the script. We will NOT see an error if not passed. Let’s see an example:


import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--blog', help="Best blog name here.")
args = parser.parse_args()

if args.blog == 'JournalDev':
    print('You made it!')

This time, we used -- in the optional argument name. When we run the script:
Python argparse Optional argument

With the -- before the optional parameter name, we can define optional parameters in any order.

The method for passing default values, help messages and data types for optional parameters is same as in positional parameters. Just a point to be noted, if no value is passed to an optional argument, it is assigned a value of None for the program.

Short names for Optional arguments with argparse

In our example above, we were very clear on what value we needed the user to be passed, optionally. That is nice but what if the descriptive name of the optional parameters in our scripts grows long. Fortunately, we can assign a short name to parameters as well. Let’s see an example snippet:


import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-b', '--blog', help="Best blog name here.")
args = parser.parse_args()

if args.blog == 'JournalDev':
    print('You made it!')

Wasn’t that simple? Just use an extra parameter in add_argument function and it’s done. let’s run this script now:
Python argparse Optional Short name

Combining Optional and Positional parameters with argparse

We can also combine the use of optional and positional command-line parameters in our script to be used. Let’s quickly see an example:


import argparse

parser = argparse.ArgumentParser()
parser.add_argument('blog', help="Best blog name here.")
parser.add_argument('-w', '--writer', help="Team Player.")
args = parser.parse_args()

if args.blog == 'JournalDev':
    print('You made it!')

if args.writer == 'Shubham':
    print('Technical Author.')

When we run the script:
Argparse example python

In this lesson, we learned about various ways through which we can manage the command-line parameters with Argbase module in Python.

Reference: API Doc

Comments

  1. mgn says:

    nicely articulated.. very helpful! great job..

  2. Manoj says:

    Well written article

  3. Shrutika says:

    simple n easy to understand …
    Thanks

  4. Mridul Sachdeva says:

    Just wanted to know if using ‘-‘ for 1 character argument and ‘–‘ for longer arguments is a convention?
    Because I tried with ‘–b’ and ‘-blog’ and it also works

  5. Salis says:

    Excellent blog, I just opened ipython terminal and followed your examples, that got me started in 15 minutes.

    thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages