Hi everyone, in this tutorial, we will see different ways to use command line arguments in Python using various examples.

What are command Line Arguments in Python?

These are the arguments that we passed along with the executing command of Python Program in the Command-line Interface (CLI) or shell. The typical syntax for this is

python script_name.py arg1 arg2 ...

In Python, we have several ways to use the command line arguments.

Using the sys module

The sys module is an in-built Module that provides us with the ability to interact with the Python interpreter on any platform using some variables and functions. One of the ways to interact with command line arguments is by using the variable sys.argv, which is a list of all the arguments passed during execution and having 1st element as the script name.

Example –

Let’s write a sample program that will take all the arguments from the command line and return their summation.

# importing the sys module
import sys

def summation(): 
    sum_cla = 0
    # loop over all command line arguments
    for i in sys.argv[1:]: 
        sum_cla = sum_cla + int(i)
    # printing the results    
    print("No. of command line arguments are: ",len(sys.argv[1:])) 
    print("Sum of command line arguments is:",sum_cla)
    return

if __name__ == "__main__":
    summation()

Output:

No. of command line arguments are: 4
Sum of command line arguments is: 16

Python argparse module

Using the argparse module gives us a lot more flexibility than using the sys.argv to interact with the command line arguments as using this we can specify the positional arguments, the default value for arguments, help message etc.

argparse is the recommended command-line parsing module in the Python standard library.

The basic code to use the argeparse module is below which does nothing if no single argument is passed and will give some sort of information if it parses the argument that is known to it like -h for help.

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

Output:

python .\cla.py -h
usage: cla.py [-h]

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

Adding positional arguments using argparse

We can add our own custom positional arguments when using the command line arguments. These type of arguments are mandatory to be passed during the execution otherwise we will get an error.

cla.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("sum",help = "It will sum the integer list passed as argument")
args = parser.parse_args()

Output:

python .\cla.py --help
usage: cla.py [-h] sum

positional arguments:
sum It will sum the integer list passed as an argument

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

Adding optional arguments using argparse

We can add our own custom optional arguments when using the command line arguments. These type of arguments are not mandatory to be passed during the execution and are generally used to provide extra optional functionalities to the user.

cla.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("weight",help = "Return -ve is integer is negative else +ve",type=int)
parser.add_argument("--verbose", action="store_true",help="negative/ positive integer")
args = parser.parse_args()

if args.verbose:
    print("Weight=", '-ve' if args.weight<0 else '+ve')
elif args.weight <0:
    print('Integer is -ve')
else:
    print('Integer is +ve')

Output:

python .\cla.py -9 --verbose
Weight= -ve

python .\cla.py 5
Integer is +ve

Python getopt module

The getopt module is a parser for command-line options whose API is similar to users of the C language getopt() function. If we want to write less code and get better help and error messages, we should consider using the argparse module that we have discussed above.

This module provides a methodgetopt()which parses the command line options and the parameter list. The first element of command-line arguments while using sys.argv is generally skipped. he basic syntax of this method is.

getopt.getopt(args, shortopts, longopts=[])
  • args – The argument list usually from the second element of Command-line interface example sys.argv[1:]
  • shortopts – The string of option letters that the script wants to recognize, with options that require an argument followed by a colon (:)
  • longopts – The list of strings with the names of the long options which should be supported.
cla.py
# importing modules
import sys
import getopt

# Defining arguments and options
arguments = sys.argv[1:]
shortopts= "svo"
longopts = ["script-name ","verbose", "output="]

# Printing different options and arguments
options, args = getopt.getopt(arguments, shortopts,longopts)
print('Options are :',options)
print('Arguments are :',args)

# Setting behaviour for options
for opt, val in options: 
    if opt in ("-s", "--script-name"):
        print ("Script name is", sys.argv[0])
    elif opt in ("-o", "--output"):
        print ("Output saved in file named", val)
    elif opt in ("-v", "--verbose"):
        print ("Verbosity is ON")

Output 1:

python .\cla.py -v --output=abc.xyz a b
Options are : [('-v', ''), ('--output', 'abc.xyz')]
Arguments are : ['a', 'b']
Verbosity is ON
Output saved in file named abc.xyz

Output 2:

python .\cla.py -s --verbose --output=opfile.txt a b
Options are : [('-s', ''), ('--verbose', ''), ('--output', 'opfile.txt')]
Arguments are : ['a', 'b']
Script name is .\cla.py
Verbosity is ON
Output saved in file named opfile.txt

So we learned how to use command-line arguments in Python and if you have any doubts or queries please ask in the comment section below.

Resources

Happy Learning 🙂

About the Author:

Avatar
Aspiring Data Scientist who loves Python Programming, Software Development and wants to Solve Real-world Problems.

Leave A Comment