How do we access command line arguments in Python?

PythonServer Side ProgrammingProgramming

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.


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 are called command line arguments.

For example

C:\users\acer>python Hello TutorialsPoint

Items separated by space are stored in a special List object called argv[]. It is defined in sys module of Python distribution.

In above example, the List object would contain:

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

In the program access these arguments by

import sys
print ("first command line argument: ",sys.argv[1])
 print ("second command line argument: ",sys.argv[2])
Updated on 13-Dec-2019 12:20:53