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! 🙂

ModuleUsePython Version
sysAll arguments in sys.argv (basic)All
argparseBuild a command line interface >= 2.3.
docoptCreate command line interfaces >= 2.5.
fire automatically generating command line interfaces (CLIs)All
optparseDeprecated 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)

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:

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:

Docopt

Docopt can be used to create command line interfaces.

Note: docopt is not tested with Python 3.6

Fire

Python Fire automatically generates a command line interface, you only need one line of code. Unlike the other modules, this works instantly.

You don’t need to define any arguments, all methods are linked by default.

To install it type:

pip install fire

Then define or use a class:

You then have the options matching the class methods:

python example.py hello
python example.py openfile filename.txt

 

Previous Post
Next Post

3 Comments

  • ashomar says:

    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.

  • İbrahim says:

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

Leave a Reply