Home » Python

How to read/process command line arguments in Python?

Here, we are going to learn how to read/process command line arguments in Python programming language?
Submitted by Sapna Deraje Radhakrishna, on March 04, 2020

The official way of reading or processing the command line arguments is by using the argparse from ArgumentParser module.

The argparse module enables is implementing the user-friendly command-line interfaces. The program defines the arguments it requires, and argparse will ascertain how to parse those out of the sys.argv? The argparse also generates the help and usage messages and issues errors when the users give the program invalid arguments.

Example:

import argparse

parser = argparse.ArgumentParser(description='Process the numbers')
parser.add_argument('integers',metavar='N', type=int, nargs='+', help='an integer for addition')
parser.add_argument('--sum',dest='addition', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.addition(args.integers))

Assuming, we have saved the above method in a file as 'argparse_example.py', it can be run at the command line and provide helpful messages.

Case 1: running the method without passing the arguments

    python argparse_example.py 
    usage: argparse_example.py [-h] [--sum] N [N ...]
    argparse_example.py: error: the following arguments are required: N

Case 2: Running the method passing the -h as argument

    python argparse_example.py -h
    usage: argparse_example.py [-h] [--sum] N [N ...]

    Process the numbers

    positional arguments:
      N           an integer for addition

    optional arguments:
      -h, --help  show this help message and exit
      --sum       sum the integers (default: find the max)

Case 3: Running the method passing the numbers (returns max of list of numbers)

    python argparse_example.py 1 2 3 4
    4

Case 4: Running the method passing the –sum argument as an argument, along with list of numbers

    python argparse_example.py 1 2 3 4 --sum
    10





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.