3 Command Line Arguments in Python

Command Line Arguments in python are simply the name given to the program in the command line shell of the operating system. Techstricks explain the three most common command-line arguments in python.

  • Using sys.argv
  • Using getopt() module
  • Using argparse() module

Also Read: 5 Ways to Remove Duplicates in Python

Using sys.argv

To manipulate different parts of the python runtime environment, variables & functions are used in this sys module whereas the sys.argv is a simple list structure. The variables used by the interpreter & function are provided access by these modules.

The main purpose of sys.argv is first it’s a list of command-line arguments. len(sys.argv) gives us the number & sys.argv[0] will be our current python script name.

The below example demonstrates a python script of addition between two numbers which are passed as a command-line argument.

# Python program to demonstrate
# command line arguments
 
 
import sys
 
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
 
# Arguments passed
print("\nName of Python script:", sys.argv[0])
 
print("\nArguments passed:", end = " ")
for i in range(1, n):
    print(sys.argv[i], end = " ")
     
# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
    Sum += int(sys.argv[i])
     
print("\n\nResult:", Sum)
techstricks@TSTLTTCE0026:-/Desktop$ python3 techstricks.py2 3 4 5
Total arguments passed: 5
Name of Python script: techstricks.py
Arguments passed: 2 3 4 5
Result: 14 

Using getopt() Module

getopt() module is used to extend the separation of the input string used by parameter validation. The getopt() module also allows short as well as long options while including a value assignment. However, this module is dependent upon the sys module & requires to process of input data correctly. Also, you must remove the first element from the list in order to use the getopt() module.

# Python program to demonstrate
# command line arguments
 
 
import getopt, sys
 
 
# Remove 1st argument from the
# list of command line arguments
argumentList = sys.argv[1:]
 
# Options
options = "hmo:"
 
# Long options
long_options = ["Help", "My_file", "Output ="]
 
try:
    # Parsing argument
    arguments, values = getopt.getopt(argumentList, options, long_options)
     
    # checking each argument
    for currentArgument, currentValue in arguments:
 
        if currentArgument in ("-h", "--Help"):
            print ("Displaying Help")
             
        elif currentArgument in ("-m", "--My_file"):
            print ("Displaying file_name:", sys.argv[0])
             
        elif currentArgument in ("-o", "--Output"):
            print (("Enabling special output mode (% s)") % (currentValue))
             
except getopt.error as err:
    # output error, and return with an error code
    print (str(err))
techstricks@TSTLTTCE0026:-/Desktop$ python3 techstricks.py -h
Displaying Help
techstricks@TSTLTTCE0026:~/Desktop$ python3 techstricks.py --Help -m
Displaying Help
Displaying file name: techstricks.py
techstricks@TSTLTTCE0026:~/Desktop$ python3 techstricks.py --My_file -o Blue
Displaying file name: techstricks.py
Enabling special output mode (Blue)

Using argparse() Module

The argparse() module is preferred almost all the time between three modules is because there are many advantages such as default value arguments, positional arguments, specifying data type arguments, etc.

# Python program to demonstrate
# command line arguments
 
 
import argparse
 
# Initialize parser
parser = argparse.ArgumentParser()
parser.parse_args()
techstricks@TSTLTTCE0026:-/Desktop$ python3 techstricks.py -h 
usage: techstricks.py [-h] 
optional arguments: 
-h, --help show this help message and exit 
techstricks@TSTLTTCE0026:-/Desktop$ python3 techstricks.py -o 
usage: techstricks.py [-h] 
techstricks.py: error: unrecognized arguments: -0

Example: Adding a description to the help message.

# Python program to demonstrate
# command line arguments
 
 
import argparse
 
msg = "Adding description"
 
# Initialize parser
parser = argparse.ArgumentParser(description = msg)
parser.parse_args()
techstricks@TSTLTTCE0026:-/Desktop$ python3 techstricks.py -h
usage: techstricks.py [-h]
Adding description
Optional arguments: 
-h, --help show this help message and exit

Example: Option value is defined

# Python program to demonstrate
# command line arguments
 
 
import argparse
 
 
# Initialize parser
parser = argparse.ArgumentParser()
 
# Adding optional argument
parser.add_argument("-o", "--Output", help = "Show Output")
 
# Read arguments from command line
args = parser.parse_args()
 
if args.Output:
    print("Displaying Output as: % s" % args.Output)
techstricks@TSTLTTCE0026:-/Desktop$ python3 techstricks.py -o
Green Displaying Output as: Green
techstricks@TSTLTTCE0026:-/Desktop$ python3 techstricks.py -0
usage: techstricks.py [-h] [-o OUTPUT] 
techstricks.py: error: argument -o/--output: expected one argument

Bookmark us to access this page whenever you need.

We will be happy to hear your thoughts

      Leave a reply

      Techs Tricks
      Logo
      Reset Password
      Shopping cart