Python

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:
Complete Python Bootcamp: Go from zero to hero in Python

How to use command line arguments in python?

We can use modules to get arguments.

Which modules can get command line arguments?

ModuleUsePython version
sysAll arguments in sys.argv (basic)All
argparseBuild a command line interface>= 2.3
docoptCreate command line interfaces>= 2.5
fireAutomatically generating command line interfaces (CLIs)All
optparseDeprecated< 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: Complete Python Bootcamp: Go from zero to hero in Python

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

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:
  
import fire

class Program(object):
def hello(self):
print("Hello World")

def openfile(self, filename):
print("Opening file '" + filename + "'")

if __name__ == '__main__':
fire.Fire(Program)


You then have the options matching the class methods:
python example.py hello
python example.py openfile filename.txt

 

Previous Post Next Post

Cookie policy | Privacy policy | ©