How to Parse Arguments from the Command Line using argparse in Python 3
Tags: python, beginners
Published: 2020-12-26 16:13:41

Having command line parameters is an essential mechanism to manage the behaviour of your application but it can get complex to validate and extract the arguments.  In our previous article on arguments ([How to use argv parameters in Python](https://pythonhowtoprogram.com/how-to-use-argv-and-argc-command-line-parameters-in-python/?utm_source=dev.to&utm_medium=cp&utm_campaign=reflink)), we went over how to use command line parameters with sys.argv. This is a useful module, but we will come across cases where we want to do more than just that. If you code enough in Python, you are most likely going to want to let users provide values for variables at runtime.

This is where argparse comes in.  In this article, we are going to look into argparse - what it is. why we use it and how we parse arguments using it.

argparse is a python module whose primary purpose is to create command line interfaces. This module was released as a replacement for the getopt and optparse modules because they lacked some important features.

##How to Parse Arguments with argparse

To understand how argparse works and how we go about making our own command line interfaces, we will begin with a simple example illustrated below:

```
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", required=True)
args = parser.parse_args()
print(f'Hi {args.name} , Welcome ')
```

Confusing? Yes, I know. But let's break this down line by line:

* We initially import the argparse module
* We then initialize the ArgumentParser object as parser
* We add the only argument --name, here we must specify both the shorthand and longhand versions. Either can be used when the program is run
* We stipulate that this argument is required
* We execute the parse_args() method
* We output the parsed argument

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0yy6qpx0mep1b9mbqc28.png)

We get the output of our print statement plus the parsed argument. But what would happen if we ran the program but didn't give any arguments?  We will try that next:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2lmpsq1obtco0opjn8oi.png)

We got an error message, explaining the usage of the program and the arguments that are required. But we never added that to our code, did we? Well, not explicitly. When we added arguments for the program, argparse generates the error message if those arguments ate not given.

Looking at the output once again, you will notice there is another argument,  one that we did not give -h. This is an optional argument that the program accepts. It serves as a sort of help command to describe what is required by the program. 

Let's parse that argument to see what output we get:

![filleee](https://dev-to-uploads.s3.amazonaws.com/i/36763ge5yqs5j7hvqqyg.png)

As we see, parsing the -h argument gives a bit more detailed explanation of the program. Armed with a basic understanding of argparse we can look at another example.

We are going to code our own program that simulates the same operation as ls:

```
# Import the argparse library
import argparse

import os
import sys

my_parser = argparse.ArgumentParser(description='List all the contents of a folder')

my_parser.add_argument('Path',
                       metavar='path',
                       type=str,
                       help='the path to list')

args = my_parser.parse_args()

input_path = args.Path

if not os.path.isdir(input_path):
    print('The path specified does not exist')
    sys.exit()

print('\n'.join(os.listdir(input_path)))
```

We need to import a number of modules first namely os, sys, and argparse. After that we:

* create the parser and assign it the name my_parser
* add the necessary arguments - in this case, path.  
* We also specify the type of the argument as string which tells argparse to check the type automatically
* execute the parse_args() function   
* create a variable named input_path and assign it args.Path - calling path on the parser
* run a check if the parsed directory does not exist and display an error message if it doesn't 
* we output the inputted directory
 
We are running the program on the same directory as before:

![list-of--1024x319](https://dev-to-uploads.s3.amazonaws.com/i/8fw6x2tgeixh5laxmudi.png)

## Conclusion
There are many other things you can do - the original article came from [Python How To Program: Argparse library article](https://pythonhowtoprogram.com/how-to-parse-arguments-from-the-command-line-using-argparse-in-python-3/?utm_source=dev.to&utm_medium=cp&utm_campaign=ctalink) where you can find the complete post.