Nov 10, 2018

How to accesse Command-Line Arguments in Python

Python provides a getopt module that helps you parse command-line options and arguments.
$ python arg1 arg2
The Python sys module provides access to any command-line arguments via the sys.argv:
  • sys.argv is the list of command-line arguments.
  • len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.


import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Run it with
$ python arg1 arg2

Number of arguments: 3 arguments.
Argument List: ['', 'arg1', 'arg2']

See more:

How to parse Command-Line Arguments in Python