Command Line Arguments are the arguments that are specified after the name of the program in the command line shell of the operating system. Python gives different ways of dealing with these types of arguments. There are three most common here which are below:
1. sys.argv
2. getopt module
3. argparse module
1. sys.argv
It is used to control various parts of the Python runtime environment and provide variables and functions. This module gives access to various variables used by the interpreter and to functions that relate powerfully with the interpreter.
The main purpose of sys.argv is:
· It is a list of command line arguments.
· len(sys.argv) provides the number of command line arguments.
· sys.argv[0] is the name of the current Python script.
Example: Adding two numbers by Python script and the numbers are passed as command-line arguments.
# 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)
Output:
2. getopt module
Python getopt module is like as the getopt() function of C. Dissimilar to sys module getopt module expands the detachment of the input string by parameter approval. It permits both short and long alternatives including a value assignment. But, this module requires the utilization of the sys module to process input information appropriately. To utilize getopt module, it is required to expel the first element from the list of command-line arguments.
Syntax: getopt.getopt(args, options, [long_options])
Parameters:
args: List of arguments to be passed.
options: String of option letters that the script want to know. Options that need an argument should be followed by a colon (:).
long_options: List of string with the name of long options. Options that need arguments should be followed by an equal sign (=).
Return Type: Returns value consisting of two elements i.e. one is a list of (option, value) pairs and second is the list of program arguments left after the option list was exposed.
Example:
# 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 ("Diplaying 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))
3. argparse module
argparse module is a superior option than the above two options as it provides lots option like positional arguments, default value for arguments, help message, specifying data type of argument etc.
Example 1: Basic use of argparse module.
# command line arguments
import argparse
# Initialize parser
parser = argparse.ArgumentParser()
parser.parse_args()
Example 2: Adding description to the help message
# command line arguments
import argparse
msg = "Adding description"
# Initialize parser
parser = argparse.ArgumentParser(description = msg)
parser.parse_args()
Comments