Python Parsing Command Line Arguments

Do you like this?

Summary:
This example shows you how to parse command line arguments using argparse library.


Content:

argparse is a Python library which is an upgrade of the library optparse. Below is an example on how to handle the arguments.

Suppose the following line is what we want to parse from the command line: 
python your-program.py -u username -p password python your-program.py -u username -p password -v python your-program.py -u username -p password --verbose python your-program.py --username username --password password --verbose
The following code can handle all the above command line inputs:
import argparse, sys

parser = argparse.ArgumentParser()
parser.add_argument("-u", "--username", action="store", type=str)
parser.add_argument("-p", "--password", action="store", type=str)
parser.add_argument("-v", "--verbose", action="store_true", dest="verbose")

args =  parser.parse_args(sys.argv[1:])
print args.username
print args.password
print args.verbose
There are a few important observations here:
  • sys.argv[1:] has to be use because sys.argv[0] is the name of your python file
  • The name of the attribute such as args.username is determined by dest attribute in the method add_argument()
  • The data type of attributes such as args.username is determined by type attribute in the method add_argument()

 
comments powered by Disqus