Parsing command line arguments in python

Python is a very popular language for many reasons and one of them is the ability to use it for quick scripting or for an enterprise application. Professionally, I have used python for writing many scripts; some that are quick and temporary, and others that are more complex and long-term.

Whatever the purpose of the script, most of them start with parsing command line arguments. It’s always a good idea to allow users to customize the behavior of script by passing in different values for command line arguments. For example, if you have a script that runs some data quality checks against a database, you might want to pass an argument that decides for which day to run the checks.

So, how do you parse command line arguments in python? Python has a built-in module called argparse that does the job for you.

 

First, you need to instantiate the parser:

import argparse
parser = argparse.ArgumentParser(description = 'tutorial for parsing command line arguments in python')

Then, you define the arguments that you want to be parsed. For demonstration, we will have two arguments. Our first argument is check_date which is the date for which you want your script to run and our second argument is email which will be the email address where you want your alert to be sent.

parser.add_argument('--check_date', action='store', required=True, choices=('20180101', '20180301'), help='Date for which we want to run checks')
parser.add_argument('--email', dest='email_address', default='default@gmail.com', action='store', help='Email address you want to send alert at')

When defining list of arguments, you can specify different options. Here are the important ones:

  • dest: name of the variablesthat will store the passed value
  • help: information displayed when –help is used
  • type: type of the value passed. Default is string.
  • required: specifying whether the argument is required or not
  • choices: list containing valid values for argument
  • default: default value for an argument
  • action: action to take after value is passed

Some patients pills viagra canada on Lipitor complain of muscle aches, and these seem to correlate well with a rise of the muscle enzyme creatine kinase in the blood, indicating some degree of erectile dysfunction condition. The fruity flavors of jelly and soft tabs are available in many delicious viagra without prescriptions uk flavors including orange, apple, strawberry, pine apple etc. The body is interconnected and cheapest cialis pop over to these guys often when a problem exists which prevents foods from getting into the intestinal tract. Luckily there are powerful and efficient natural extracts that battle sexual price of viagra pills dysfunction; One of them is Gingko Biloba that increases the flow of blood going towards reproductive area.
Then, you need to parse the arguments:

args = parser.parse_args()

Finally, you can access the arguments:

args = parser.parse_args()

For demonstration purposes, I will print out the values:

print('Running checks for date: {check_date} and sending alert to: {email}'.format(check_date=args.check_date, email=args.email_address))

This is what my script: args_parse.py looks like:

import argparse

# Instantiate parser
parser = argparse.ArgumentParser(description = 'tutorial for parsing command line arguments in python')

# Add arguments that will be parsed by the script
parser.add_argument('--check_date', action='store', required=True, choices=('20180101', '20180301'), help='Date for which we want to run checks')
parser.add_argument('--email', dest='email_address', default='default@gmail.com', action='store', help='Email address you want to send alert at')

# Parse arguments
args = parser.parse_args()

print('Running checks for date: {check_date} and sending alert to: {email}'.format(check_date=args.check_date, email=args.email_address))

Here are some different ways to execute the script:

$python parse_args.py --check_date 20180101 --email abc@gmail.com
>> Running checks for date: 20180101 and sending alert to: abc@gmail.com

$python parse_args.py --check_date 20180101 --email hola@hotmail.com
>> Running checks for date: 20180101 and sending alert to: hola@hotmail.com

The script will fail if you provide a value that is not valid:

$ python parse_args.py --check_date 20180106 --email hola@hotmail.com
usage: parse_args.py [-h] --check_date {20180101,20180301}
                     [--email EMAIL_ADDRESS]
parse_args.py: error: argument --check_date: invalid choice: '20180106' (choose from '20180101', '20180301')

The script will also fail if you don’t provide value for a required argument:

$ python parse_args.py --email hola@hotmail.com
usage: parse_args.py [-h] --check_date {20180101,20180301}
                     [--email EMAIL_ADDRESS]
parse_args.py: error: the following arguments are required: --check_date

If you don’t specify an argument but you have a default value set, then that value will be used:

$ python parse_args.py --check_date 20180101
>> Running checks for date: 20180101 and sending alert to: default@gmail.com

Finally, you can always use –help option to get more information about the arguments:

$ python parse_args.py --help
usage: parse_args.py [-h] --check_date {20180101,20180301}
                     [--email EMAIL_ADDRESS]

tutorial for parsing command line arguments in python

optional arguments:
  -h, --help            show this help message and exit
  --check_date {20180101,20180301}
                        Date for which we want to run checks
  --email EMAIL_ADDRESS
                        Email address you want to send alert at

I hope you found this post helpful!

Leave a comment

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