Python

How to parse arguments on command-line in Python

The command-line arguments are used to pass data in the program at the time of program execution. This feature is available on most of the popular programming languages. But the processing of command-line arguments is different for different languages. The arguments values are given with the program name at the time of running the program. Python language supports this feature. How command-line arguments are parsed in Python script is shown in this article.

Parsing command-line argument using sys module

Command-line arguments are stored into a list using sys module.  sys.argv is used to read the values of the command-line arguments. The total number of command-line arguments can be counted by using len() function. The use of this module is described in the part of the article.

Example 1: Reading the number of arguments and argument values

Create a file with the following python script.  Here, the command-line argument values are stored in the variable, argv like other languages. len() method counts the total numbers of arguments passed at the time of executing the script. Argument values are printed as an array at the end of the script.

# Import sys module
import sys

# Print total number of arguments
print('Total arguments:', len(sys.argv))
print('The argument values are:', str(sys.argv))

Output:

The above script is executed here using four command-line arguments. The first argument is the script name and others are numeric values. The following output will appear after running the script.

Example 2: Reading argument values using the loop

In the previous example, argument values are printed as an array. Create a file with the following script to print the type of argument variable and print each argument value in each line by using for loop.

# Import sys module
import sys

# Print the type of the variable, sys.argv
print(type(sys.argv))

# Print each command-line argument in each line
print('The command line arguments are:')
for i in sys.argv:
  print(i)

Output:

The above script is executed by providing three arguments with the script name. The following output will appear after running the script.

Parsing command-line argument using getopt module

Getopt module is used to parse command-line arguments with the options. getopt() method of this module is used for reading the arguments. This method has three arguments. The first two arguments are mandatory and the last argument is optional. The uses of these arguments are given below.

args: It contains the argument taken from the command-line argument.

short_option: It can be any letter that passes with the argument.

long_option: It is used to define long options with two parts. These are the option name and option value.

Syntax: getopt.getopt(args, short_option, [long_option])

Example 3: Reading argument values using short getopt options

getopt module contains more features than sys module. The following example shows how short options can be used in getopt() method. argv variable will store the command-line arguments by omitting the script name. Next, two options are defined in the getopt() method that can be used with the argument at the run-time. If any error occurs then an error message will display.

# Import getopt module
import getopt

# Import sys module
import sys

# Store argument variable omitting the script name
argv = sys.argv[1:]
 
try:
  # Define getopt short options
  options, args = getopt.getopt(argv, 'x:y:')

  # print the options and argument
  print(options)
  print(args)
 
except getopt.GetoptError:
 
  # Print the error message if the wrong option is provided
  print('The wrong option is provided')

  # Terminate the script
  sys.exit(2)

Output:

Run the script without any argument, arguments with correct options and arguments with the wrong option.

Example 4: Reading argument values using short and long getopt options

This example shows how both short and long options can be used with the argument values. It will add two numbers when ‘-a’ or ‘–add’ will be used as an option and subtract two numbers when ‘-s’ or ‘–sub’ will be used as an option at the run-time.

# Import getopt module
import getopt

# Import sys module
import sys

# Store argument variable omitting the script name
argv = sys.argv[1:]

# Initialize result variable
result=0
 
try:
 
  # Define getopt short and long options
  options, args = getopt.getopt(sys.argv[1:], 'a:s', ['add=','sub='])
 
  # Read each option using for loop
  for opt, arg in options:
    # Calculate the sum if the option is -a or --add
    if opt in ('-a', '--add'):
      result = int(argv[1]) + int(argv[2])

    # Calculate the suntraction if the option is -s or --sub
    elif opt in ('-s', '--sub'):
      result = int(argv[1]) - int(argv[2])
 
  print('Result = ', result)

except getopt.GetoptError:

  # Print the error message if the wrong option is provided
  print('The wrong option is provided')
 
  # Terminate the script
  sys.exit(2)

Output:

Run the script without any arguments and options, arguments with ‘-a’ option, arguments with ‘-s’ option and arguments with the wrong option.

Parsing command-line argument using argparse module

Argparse module contains lots of options to read command-line arguments. Default argument values, the argument with the data type, positional arguments, help message, etc. can be provided by this module.

Example 5: Reading command-line arguments using argparse

The following example shows the use of argparse module for reading command-line argument. Here, two options are defined for reading command-line arguments. These are ‘-n’ or ‘–name’ and ‘-e’ or ‘–email’. If the user provides any wrong argument then it will show an error with a usage message. If the user provides correct options with the arguments then it will display the argument values. if the user runs the script with ‘–help’ option then it will provide necessary message to run the script.

# Import argparse module
import argparse

# Import sys module
import sys

# Declare function to define command-line arguments
def readOptions(args=sys.argv[1:]):
  parser = argparse.ArgumentParser(description="The parsing commands lists.")
  parser.add_argument("-n", "--name", help="Type your name.")
  parser.add_argument("-e", "--email", help="Type your email.")
  opts = parser.parse_args(args)
  return opts

# Call the function to read the argument values
options = readOptions(sys.argv[1:])
print(options.name)
print(options.email)

Output:

Run the script with wrong option, correct option and help option.

Conclusion:

Various ways of reading command-line arguments are explained in this tutorial by using three python modules. I hope, this tutorial will help the coder who wants to read data using command-line arguments in python.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.