Command line arguments

What are command line arguments in python?

In the command line, we can start a program with additional arguments.
These arguments are passed into the program.

Python programs can start with command line arguments. For example:

$ python program.py image.bmp

where program.py and image.bmp is are arguments. (the program is Python)

Related Course:

How to use command line arguments in python?

We can use modules to get arguments.

Which modules can get command line arguments?

Note: Choose a module to get arguments. Examples below, try all! ­čÖé

Module Use Python Version
sys All arguments in sys.argv (basic) All
argparse Build a command line interface >= 2.3.
docopt Create command line interfaces >= 2.5.
optparse Deprecated Deprecated (< 2.7)

Sys argv

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')

Related Course:

Argparse

If you need more advanced parsing, you can use argparse.
You can define arguments like (-o, -s).

The example below parses parameters:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-o','--open-file', help='Description', required=False)
parser.add_argument('-s','--save-file', help='Description', required=False)

args = parser.parse_args()

print(args.open_file)
print(args.save_file)

Docopt

Docopt can be used to create command line interfaces.

from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Example 1.0')
    print(arguments)
Note: docopt is not tested with Python 3.6

 

Previous Post
Next Post

3 Replies to “Command line arguments”

  1. 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 *