Learn Python Programming

Python – Command Line Parameters

In Python, it is possible to pass arguments to python programs when they are executed.

The brackets which follow main are used for this purpose.

.argv refers to the number of arguments passed, and argv[] is a pointer array which points to each argument which is passed to main.

The python sys module provide access to many command-line arguments via the sys.argv.

This servers two purpose:

  • sys.argv is the list of command-line arguments.
  • len(sys.argv) is the number of command-line arguments.
#let filename: command_line_argument.py

import sys

print('Number of arguments: ', len(sys.argv))
print('Argument list: ', sys.argv)

#now run above script as follows −
$ python command_line_argument.py arg1 arg2 arg3

Number of arguments:  4
Argument list:  ['ex1.py', 'arg1', 'arg2', 'arg3']