How do we access command line arguments in Python?


Command line is the place where executable commands are given to operating system. A Python script can be executed by writing its name in front of python executable in the command line.

C:\users\acer>python test.py

If you want some data elements to be passed to Python script for its processing, these elements are written as space delimited values in continuation to name of script. This list of space delimited values is called command line arguments.

For example,

C:\users\acer>python test.py Hello TutorialsPoint

When there exists a way to pass arguments through the command line, there must also exist a way to accept those arguments passed. There are various ways to access them

  • Using a List Object argv[]

  • Using argparse Module

  • Using getopt Module

Using argv[] List Object

Python contains a special list object called argv[] that stores these command line arguments passed. They are distinguished by a space character. argv[] is defined in sys module of Python distribution.

Example

For example, let us assume we are trying to pass two strings as arguments to the python file ‘test.py’ while executing it through command line.

C:\users\acer>python test.py Hello TutorialsPoint

This program’s List object would then contain the following −

sys.argv[]=[‘test.py’, ‘Hello’, ‘TutorialsPoint’]

test.py:

In the python program, access these arguments shown as follows −

import sys

print ("first command line argument: ",sys.argv[1])
print ("second command line argument: ",sys.argv[2])

Output

The output will be produced as −

first command line argument: Hello
second command line argument: Tutorialspoint

Using argparse Module

The argparse module is a built-in module that reduces boiler plate code and makes your code more robust. It is better than using the special List Object argv[] as the argparse module handles all the standard use cases, including subcommands, and generates the help and its usage for you, checks and sanitizes the user input which argv[] fails to do

Example

In the following example, let us try to execute the following python program ‘test.py’ through the command line.

import argparse

parser = argparse.ArgumentParser("simple_example")
parser.add_argument('student_id', type=str, help='Show student_id')
args = parser.parse_args()

print("The Student Exists with ID:")
print(args.student_id)

In the command line, use the following command to execute the program above,

Output

python test.py 2000133

The output will be produced as follows −

The Student Exists with ID:
2000133

Using getopt Module

Python provides the getopt module is used to parse the command line arguments in a program. The API is designed similar to the getopt() function in C programming language, therefore, it supports same conventions as the function.

This module provides a method with the same name, getopt(). It is used to access the command line arguments. Following is the syntax of this method −

getopt.getopt(args, shortopts, longopts=[])

As we can see, getopt() method accepts three parameters: args, shortopts and longopts

Where,

  • args is the list of command line arguments

  • args is the list of command line arguments

  • Longopts is a list of strings with the names of long options. Options that require arguments should be followed by an equal sign (=).

This method is equivalent to sys.args[1:], i.e., it does not access the reference of the program.

Example

Following example demonstrates the usage of getopt.getopt() method to parse through the command line arguments.

import sys
import getopt

def welcome():
   first_arg = None
   next_arg = None
   argv = sys.argv [1:]
   try:
      opts , args = getopt.getopt (argv, "f:n:")
   except:
      print ("Error")
   for opt , arg in opts:
      if opt in ['-f']:
         first_arg = arg
   elif opt in ['-n']:
         next_arg = arg
   print (first_arg + " " + next_arg)
welcome()

Output

Use the following command to execute the program above by passing two arguments through command line −

python test.py -f Hello -n Tutorialspoint!

The output is obtained as −

Hello Tutorialspoint!

Updated on: 21-Apr-2023

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements