FahmidasClassroom

Learn by easy steps

Fimage

The data can be taken in Python by using the input() function and the command-line arguments. You can run the Python script from the terminal or by using any popular GUI editor. Many types of modules exist in Python to take command-line argument values in Python. The uses of some commonly used Python modules to take command-line argument values from the terminal have been shown in this tutorial.

Use of sys.argv module:

The sys.argv module is the most commonly used Python module to take command-line argument values in Python. The number of command-line argument values and each argument value can be read easily by using sys.argv[] array. The use of this module has been shown in the following example.

The script will count the total number of command-line arguments to check whether any argument value is given or not and the way of reading the argument values has been shown using the for loop.

#Import module
import sys

#Count the number of total arguments
total_arg = len(sys.argv)

#Check the total number of arguments
if total_arg < 2:
    print ("No argument value has been given.")
else:
    print ("\nArgument values with the script name are:")
    #Print the argument values by iterating the array 
    for value in sys.argv:
        print (value)
    
    print ("\nArgument values are:")
    #Print the argument values by accessing the array index
    for index in range(1, total_arg):
        print (sys.argv[index])

The following output will appear if no argument value is given.

p11

The following output will appear for two argument values, 34 and 80.

p12

Use of the getopt module:

The getopt module is used to provide the command-line argument values with the option. This module can take argument values in a more better way and it requires the sys module to work. The syntax of this module is given below.

Syntax:

getopt.getopt (args, short_options [,long_options])

The first argument of the getopt() function is mandatory that contains the command-line argument list. The second argument is optional and it is used to define the short options for the argument. The third argument is also optional and it is used to define the long options for the argument. The use of this module to take command-line arguments with the short and long options has been shown in the following example.

The first argument contains the script name. The way of removing the script name from the argument list has been shown in the following argument. Next, the way of reading the command-line arguments with the short and long options has been shown.

#Import required modules
import getopt, sys

#Delete the script name from the argument list
argList = sys.argv[1:]

#Read the argument values with the short and long options
options, values = getopt.getopt(argList, "up", ["username", "password"])

#Read the options and values
for Argument, val in options:
     #Check the options
     if Argument in ("-u", "--username"):
         print ("Username: %s" %values[0])
     elif Argument in ("-p", "--password"):
         print ("Password: %s" %values[1])
     else:
         print ("The option is/are invalid.")

The script has been executed with two short options and argument values.

p21

The script has been executed with one short option, one long option and two argument values.

p22

The script has been executed with two long options and argument values.

p23

Use of argparse module:

The argparse module is another useful module to read command-line argument values in Python. This module can parse the command-line argument values without using sys modules. It has more features than other modules. The argument values can be read with the data type by using this module. The use of this module has been shown in the following example.

Three command-line argument names with the datatype have been defined in the script. If no argument is passed then an error message will be displayed, otherwise the argument values will be parsed and printed in the output.

#Import module
import argparse

#Set the parser description
parser=argparse.ArgumentParser(description="Emplyee Profile Information")

#Define the argument names
parser.add_argument("name", type=str)
parser.add_argument("designation", type=str)
parser.add_argument("salary", type=int)

#Define the argument objects
args=parser.parse_args()

#Read the argument values
emp_name=args.name
emp_post=args.designation
emp_sal=args.salary

#Print the argument values
print ("Name: %s" %emp_name)
print ("Designation: %s" %emp_post)
print ("Salary: %s" %emp_sal)

The following error message will be displayed if no argument is passed.

p31

The following output will appear if three argument values are passed.

p32

Conclusion:

The uses of the most commonly used modules to read the command-line argument values in different ways have been explained in this tutorial with multiple Python examples. Python has many other modules to do this task, such as click module, docopt module, etc.