top of page

How do I Pass Command Line Arguments In Python

Updated: Mar 17, 2021


Command Line Arguments

# Python provides a oldest one is the sys module. In terms of names, and its usage, it relates directly to the C library (libc). The second way is the getopt module which handles both short, and long options, including the evaluation of the parameter values.Furthermore, two lesser-known ways exist.


The sys module implements the command line arguments in a simple list structure named sys.argv.


# file name pythonScript.py

#!/usr/bin/python

import sys

# Zero index points to the name of script file print ("Script file name: ", sys.argv[0])

# sys.argv is the list of arguments print ("The arguments are: " , str(sys.argv))

# length of arguments print ("Number of arguments: ", len(sys.argv))

 
  • sys.argv is the list of command-line arguments.

  • len(sys.argv) is the number of command-line arguments.

  • sys.argv[1], sys.argv[2], sys.argv[3] are argument 1,argument 2 and argument 3 respectively .

Here sys.argv[0] is the program ie. script name.

Example

$ python pythonScript.py arg1 argv2 argv 3

Output:

Script file name: pythonScript.py

The arguments are: arg1 argv2 argv 3

Number of arguments: 4






bottom of page