Command line arguments

Python programs can be started using command line arguments. For example:

$ python program.py image.bmp

where image.bmp is an argument. You can choose any argument you want in your program.

(You only want to do this with command line programs)

Command line arguments in Python
You can get access to the command line parameters using the sys module.  len(sys.argv) contains the number of arguments.  To print all of the arguments simply execute str(sys.argv)

#!/usr/bin/python

import sys

print('Arguments:', len(sys.argv))
print('List:', str(sys.argv))

Example:

$ python3 example.py image.bmp color
Arguments: 3
List: [‘example.py’, ‘image.bmp’, ‘color’]

Storing command line arguments
You can store the arguments given at the start of the program in variables.
For example, an image loader program may start like this:

#!/usr/bin/python
#!/usr/bin/python

import sys

print('Arguments:', len(sys.argv))
print('List:', str(sys.argv))

if sys.argv < 2:
    print('To few arguments, please specify a filename')

filename = sys.argv[1]
print('Filename:', filename)

Another example:

('Arguments:', 2)
('List:', "['example.py', 'world.png']")
('Filename:', 'world.png')

Line charts
Tuples

3 thoughts on “Command line arguments

  1. Reply
    İbrahim - April 15, 2016

    Why is bmp is an argument , in my computer only a .py extensional file came up ?

    1. Reply
      admin - April 26, 2016

      I write a bmp filename in the command, this is the only reason. By default only .py files should come up.

  2. Reply
    ashomar - May 11, 2016

    There is two issue with second example code:
    1. In line # 9: it should be like this: if len(sys.argv) < 2: NOT like this: if sys.argv < 2:
    2. Line #12 & 13 should be in 'else' statement like this:
    else:
    filename = sys.argv[1]
    print('Filename:', filename)

    thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *