Python Tutorial: Parsing command-line arguments

python parsing command-line arguments

In this tutorial, you’ll learn how to parsing command-line argument in python using the argparse module. this module (argparse module) helps to write user-friendly command-line interfaces.

The argparse module automatically generates help and usage messages, specifying the data type of argument, managing errors, and issues

What is Python?

Python is a scripting language and that is used for creating engineering-analysis tools, web development (server-side), software development, system scripting, and animation software. It designed by Guido van Rossum and first released in 1991. It’s an interpreted, High-level. General-purpose language. Python runs on Windows, Mac OS, and Linux.

Python Tutorial: Introduction for Beginners (Part 1)
Python Tutorial: Introduction for Beginners (Part 2)
Python Tutorial: How to Connect MySQL Database in Python
Python Tutorial: Python GUI Programming (Tkinter)
Python Tutorial: Send Emails Using Python
Python Tutorial: Django Tutorial for Beginners

(Python: parsing command-line arguments)
import argparse

import argparse

First Guide

basic.py

import argparse

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


"""
D:argparse>python basic.py -h
usage: basic.py [-h]

optional arguments:
  -h, --help  show this help message and exit
"""

Open Command Prompt and navigate to the directory where you saved “basic.py” python file. then enter the following command and press enter to view help page.

python basic.py -h or python basic.py --help

Print Help in Startup

printHelp.py

import argparse

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

parser.print_help()

"""
D:argparse>python printHelp.py
usage: printHelp.py [-h]

optional arguments:
  -h, --help  show this help message and exit
"""

Open Command Prompt and navigate to the directory where you saved “printHelp.py” python file. then enter the following commands and press enter.

python printHelp.py

Add Description

basicDesc.py

import argparse
parser = argparse.ArgumentParser(
  description="This is a description",
  epilog="This is a additional description"
)
args = parser.parse_args()


"""
D:argparse>python basicDesc.py -h
usage: basicDesc.py [-h]

This is a description

optional arguments:
  -h, --help  show this help message and exit

This is a additional description
"""

Open Command Prompt and navigate to the directory where you saved basicDesc.py” python file. then enter the following command and press enter.

python basicDesc.py -h

Positional arguments

basicPosit.py

import argparse
parser = argparse.ArgumentParser()

parser.add_argument("value", help="this is a help text")
args = parser.parse_args()

print (args.value)

"""
D:argparse>python basicPosit.py -h
usage: basicPosit.py [-h] value

positional arguments:
  value       this is help text

optional arguments:
  -h, --help  show this help message and exit
"""

Open Command Prompt and navigate to the directory where you saved basicPosit.py” python file. then enter the following command and press enter.

python basicPosit.py [value]
--------------------------------
python basicPosit.py Ctechf.com

basicPositJoinS.py (Join 2 Strings)

import argparse
parser = argparse.ArgumentParser()

parser.add_argument("fname", help="first name")
parser.add_argument("lname", help="second name")

args = parser.parse_args()

print("Hello {} {}!".format(args.fname, args.lname))


"""
D:argparse>python basicPositJoinS.py -h
usage: basicPositJoinS.py [-h] fname lname

positional arguments:
  fname       first name
  lname       second name

optional arguments:
  -h, --help  show this help message and exit
"""

Open Command Prompt and navigate to the directory where you saved “basicPositJoinS.py” python file. then enter the following command and press enter.

python basicPositJoinS.py fname lname
--------------------------------------
python basicPositJoinS.py EMILY Smith

basicPositAddN.py (Add 2 numbers)

import argparse
parser = argparse.ArgumentParser()

parser.add_argument("x", type=int, help="first number")
parser.add_argument("y", type=int, help="second number")

args = parser.parse_args()

result = args.x + args.y

print("{} + {} = {}".format(args.x, args.y, result))

"""
D:argparse>python basicPositAddN.py -h
usage: basicPositAddN.py [-h] x y

positional arguments:
  x           first number
  y           second number

optional arguments:
  -h, --help  show this help message and exit
"""

Open Command Prompt and navigate to the directory where you saved basicPositAddN.py” python file. then enter the following command and press enter.

python basicPositAddN.py x y
-------------------------------
python basicPositAddN.py 12 20

Optional arguments

basicOpt.py

import argparse
parser = argparse.ArgumentParser()

parser.add_argument("-n", "--name", help="name of the user")

args = parser.parse_args()

if args.name:
    print("Hello {}".format(args.name))
else:
    print("Hello")


"""
D:argparse>python basicOpt.py -h
usage: basicOpt.py [-h] [-n NAME]

optional arguments:
  -h, --help            show this help message and exit
  -n NAME, --name NAME  name of the user
"""

Open Command Prompt and navigate to the directory where you saved basicOpt.py” python file. then enter the following command and press enter.

python basicOpt.py -n [NAME] or python basicOpt.py --name [Name]
-----------------------------------------------------------------
python basicOpt.py -n George or python basicOpt.py --name George

Combine Positional and Optional arguments

basicPosOpt.py

import argparse
parser = argparse.ArgumentParser()

parser.add_argument("name", help="name of the user")
parser.add_argument("-a", "--age", type=int, help="age of the user")

args = parser.parse_args()

if args.age:
    print("My name is {}, I'm {} years old".format(args.name, args.age))
else:
    print("My name is {}".format(args.name))


"""
D:argparse>python basicPosOpt.py -h
usage: basicPosOpt.py [-h] [-a AGE] name

positional arguments:
  name               name of the user

optional arguments:
  -h, --help         show this help message and exit
  -a AGE, --age AGE  age of the user
"""

Open Command Prompt and navigate to the directory where you saved “basicPosOpt.py” python file. then enter the following commands and press enter.

python basicOpt.py NAME
and
python basicOpt.py NAME -a 25 or python basicPosOpt.py Name --age 25
------------------------------------------------------------------------
python basicOpt.py George 
and
python basicOpt.py George -a 23 or python basicPosOpt.py George --age 23 

Positional and Optional arguments with Required

basicPosOptReq.py

import argparse
parser = argparse.ArgumentParser()

parser.add_argument("name", help="name of the user")
parser.add_argument("-a", "--age", required=True, type=int, help="age of the user")

args = parser.parse_args()

print("My name is {}, I'm {} years old".format(args.name, args.age))

"""
D:argparse>python basicPosOptReq.py -h
usage: basicPosOptReq.py [-h] -a AGE name

positional arguments:
  name               name of the user

optional arguments:
  -h, --help         show this help message and exit
  -a AGE, --age AGE  age of the user
"""

Open Command Prompt and navigate to the directory where you saved basicPosOptReq.py” python file. then enter the following commands and press enter.

python basicPosOptReq.py NAME -a AGE or python basicPosOptReq.py NAME --age AGE
---------------------------------------------------------------------------------
python basicPosOptReq.py George -a 22 or python basicPosOptReq.py George --age 22

action append

basicAction.py

import argparse
parser = argparse.ArgumentParser()

parser.add_argument("-n", "--name", required=True, action="append", help="name of the user")

args = parser.parse_args()

for name in args.name:
    print("My name is {}".format(name))

"""
D:argparse>python basicAction.py -h
usage: basicAction.py [-h] -n NAME

optional arguments:
  -h, --help            show this help message and exit
  -n NAME, --name NAME  name of the user
"""

Open Command Prompt and navigate to the directory where you saved basicPosOptReq.py” python file. then enter the following commands and press enter.

python basicAction.py -n NAME1 -n NAME2 -n NAME3 .... -n NAMEN 
or 
python basicAction.py --name NAME1 --name NAME2 --name NAME3 .... --name NAMEN 
---------------------------------------------------------------------------------
python basicAction.py -n George -n Norma -n Suis
or 
python basicAction.py --name George--name Norma --name Suis

Choices

basicCho.py

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-c', '--country', choices=['0', '1', '2', '3'],
                    help="Select country")

args = parser.parse_args()
select = args.country

if select == '0':
    print("0 - United State")
elif select == '1':
    print("1 - Canada")
elif select == '2':
    print("2 - China")
elif select == '3':
    print("3 - Japan")


"""
D:argparse>python basicCho.py -h
usage: basicCho.py [-h] [-c {0,1,2,3}]

optional arguments:
  -h, --help            show this help message and exit
  -c {0,1,2,3}, --country {0,1,2,3}
                        Select country
"""

Open Command Prompt and navigate to the directory where you saved “basicCho.py” python file. then enter the following commands and press enter.

python basicCho.py -c 3 or python basicCho.py --country 3
and
python basicCho.py -c 0 or python basicCho.py --country 0

Customizing error messages

cuzError.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", help="name of the user")
parser.add_argument("-a", "--age", help="age of the user")

args = parser.parse_args()

if args.name is None:
    parser.error("--name required")
else:
    print ("name =", args.name)
    print ("age =", args.age)
    

"""
D:argparse>python cuzError.py -h
usage: cuzError.py [-h] [-n NAME] [-a AGE]

optional arguments:
  -h, --help            show this help message and exit
  -n NAME, --name NAME  name of the user
  -a AGE, --age AGE     age of the user
"""

Open Command Prompt and navigate to the directory where you saved “cuzError.py” python file. then enter the following commands and press enter.

python cuzError.py 
and
python cuzError.py -n George 
and
python cuzError.py -a 21
and
python cuzError.py -n George -a 21

Generate random text and Save

genText.py

import argparse
import random
parser = argparse.ArgumentParser()

parser.add_argument('name', help="name of the file")

parser.add_argument('-l', '--letters', default='0', help="letters")
parser.add_argument('-c', '--char', default='6', help="character")
parser.add_argument('-n', '--times', type=int, default='6', help="n times")

args = parser.parse_args()

name = args.name
char = int(args.char)
times = int(args.times)
lt = args.letters

if (lt == '0'):
    letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZYZ"
else:
    letters = args.letters

file = open(name, 'w')

for time in range(times):
    genarete = ''.join((random.choice(letters) for i in range(char)))
    file.write(genarete+'n')

file.close()


"""
D:argparsegenText>python genText.py gen.txt -h
usage: genText.py [-h] [-l LETTERS] [-c CHAR] [-n TIMES] name

positional arguments:
  name                  name of the file

optional arguments:
  -h, --help            show this help message and exit
  -l LETTERS, --letters LETTERS
                        letters
  -c CHAR, --char CHAR  character
  -n TIMES, --times TIMES
                        n times
"""

Open Command Prompt and navigate to the directory where you saved “genText.py” python file. then enter the following commands and press enter.

python genText.py gen.txt -c 20 -n 100

Source Files – https://github.com/ctechf/argparse_tutorial.git

Sources : 
https://pixabay.com/ (images) 
https://docs.python.org/3/library/argparse.html (Documentation)

Hello Friends,

Hope this post (Python Tutorial: Parsing command-line arguments (argparse)) will help you to learn something, If you enjoy my work then please share my posts with your friends and anyone who might be interested in programming and don’t forget to subscribe my mailing list.

If you had any problem with this post, please do mention it in the comment section.

Like ctechf Facebook fan page: https://www.facebook.com/ctechf

Best Free eBooks to Learn Python Programming

Free eBooks to Learn Python

Free eBooks to Learn Python, Here are 13 of the best Python eBooks for python lovers.
Download Now

How to be a Programmer

Liked it? Take a second to support CtechF on Patreon!

Leave a Reply

135 Shares
Share
Tweet
Share
Pin
Share