Argparse

Let us say you want to write some python code so that you can run it on the command line to do something.  So you might run it like

python my_code.py arguments
./my_code.py arguments

There are a number of things you should do to make this work. First you should add the following line to the top of your file.

#! /usr/bin/env python

This is called a shebang line and it tells your script what program to use to run it. It is not really necessary, but it useful for making it clear that this is a python script. Also at tend of your file you should add the following lines

if __name__=="__main__":
    main()

This line checks to see if you are running this code from the command line and then runs the program main if you are. This is important so that you can import this file without running main if you want to. On execution this file will now run the function you define as main which can be anything you want. If you want to pass arguments to main the list sys.argv can be passed to main. However, the argparse package includes functions that make argument passing easy and insure that error checking is performed and error messages generated. Here is an example of how to use argparse in main

import argparse
def main():
parser = argparse.ArgumentParser(description="Do Something.")
parser.add_argument('name',type=str,default='Jane',help='Person's Name')
parser.add_argument("--bday",help="add happy birthday",action="store_true")
args=parser.parse_args()
print("Hello {}".format(args.name))
if args.bday:
     print("Happy Birthday")

So what happens in this function. First we create a parser with the ArgumentParser function. Then we can add arguments that might be passed with the add_argument function. Arguments can be variables which will have the name of the string that you give, or they can be like keywords if you use the – – before the word. For each argument you can give the type, a default and what will be printed if the arguments are not correctly parsed. Once you have added all the arguments that you want then you parse them with parse_args() and then the variables are available for you to use as you like like args.name is used in the example above. There are many other features for your arguments you can use that are described here.

Comments are closed.