Python Command-Line Scripts: Reference

Python Command-Line Scripts: Reference

Last updated:

NOTE: This is aimed mainly at simple CLI applications in Python. For anything more complex than this, use click1

Examples use Python 3


You can call any python as a regular executable script if you add this line to the top of the file:

#!/usr/bin/env python

Get arguments

To access passed arguments, use sys.argv[1], sys.argv[2], etc

#!/usr/bin/env python

import sys

# the first argument is the script name itself
print('This script was passed', len(sys.argv)-1, 'arguments')
print('Arguments:', sys.argv[1:]) # note we're using 1:
print('Argument 1 is: ', sys.argv[1])

Sample call/output

$ ./my-script foo bar
This script was passed 2 arguments
Arguments: ['foo', 'bar']
Argument 1 is:  foo

Number of arguments passed

Use len(sys.argv)-1 (subtracting 1 because the first argument is always the scripts name itself)

1: Here is an example application created with click: jekyll-utils

Dialogue & Discussion