Skip to main content
Python 3Scripting

Using argparse for professional Argument handling in Python

By April 17, 2013May 21st, 2020No Comments

By using argparse in Python as an alternative to making use of the sys module and the argv array is a great solution to quickly give you more functionality.To understand this this we need to look at the argparse module. With minimal coding we have a –help option in the script:

First we start by importing the argparse module, and we then create an instance of the ArgumentParser object, and then parse, or read the arguments:

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

With just these three lines in place we have built the -h or –help option into the script and it looks more professional straight away. Now of course we need to add in more arguments than the built in help:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-a","--add",help="Creates local account")
args=parser.parse_args()

Notice that we have added the option ‘add’ that can be specified as -a or –add and some help text. The last line also shows that we have created the args object based on the arguments that we have read in. So we have the option but we still do not do any thing with it. In our case we do not want to make the option required as me may want to use the -d or delete option in the script; so we have to check with a conditional statement that the add item is set before we deal with it:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-a","--add",help="Creates local account")
args=parser.parse_args()
if args.add:
	print("Creating user " + args.add)

So now we can run the script args.py fred and it will echo out that we are creating the user fred. If we try to create two users args.py fred bill and error is produced as by default we expect just one argument. To fix this bug we alter the add_argument line:
parser.add_argument(“-a”,”–add”,nargs=”+”,help=”Creates local account”) the nargs entry now allows multiple arguments to –add. We are not finished yet though. The add argument is now a list that we have to iterate through, even if we have just one item in it.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-a","--add",nargs="+",help="Creates local account")
args=parser.parse_args()
if args.add:
    for u in args.add:
	print("Creating user " + u)

With this working we can now add the option to allow account deletions that will call userdel and or course modify the code so it does what we want adding and deleting users. Watch the video to see this in action.