Python – Accessing Command Line Arguments

Python provides a getopt module that helps you parse command-line options and arguments.

$ python arg1 arg2 arg3

The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purpose:

  • 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.


Consider the following script


import sys

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

Now run above script as follows:

$ python arg1 arg2 arg3

This will produce following result:

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

NOTE: As mentioned above, first argument is always script name and it is also being counted in number of arguments.

Courtesy :

Additional notes from VJ : –

If there are arguments that are provided along with the python file, then within the python file this argument can be accessed like this : –

sys.argv[1]  -> for 2nd argument
sys.argv[2] -> for 3rd argument

Note: sys.argv[0] is the python script name as mentioned above



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s