Skip to content

Command-line interface

Defining and processing a command-line interface. Uses the argparse module.

Create

Create an command-line arguments parser

Action Code Details
Define an argument parser
import argparse
parser = argparse.ArgumentParser(
  prog = 'My CLI program',
  description = 'Description of functionality here',
  epilog = 'Text at the bottom of the help file'
)

Add argument to the parser

Action Code Details
Define positional argument
parser.add_argument('file')
Define optional positional argument
parser.add_argument('dest', nargs='?')
Define positional argument accepting multiple values
parser.add_argument('files', type = str, nargs='+')
Define flag to enable a feature (default is False)
parser.add_argument('-f', '--force', action = 'store_true')
Define flag to disable a feature (default is True)
parser.add_argument('--disable', action = 'store_false')
Define string option
parser.add_argument('-s', '--source', type = str)
Define int option
parser.add_argument('--seed', type = int)
Define float option
parser.add_argument('value', type = float)
Define categorical option
parser.add_argument('answer', choices = ['a', 'b', 'c'])
Define valid path option
parser.add_argument('path', type = pathlib.Path)
Define openable file option
parser.add_argument('file', type = open)
Define writable file option
parser.add_argument('dest', type = argparse.FileType('w'))
Define option that takes a value
parser.add_argument('--seed')
Define option that optionally takes a value
parser.add_argument('--seed', nargs = '?')
Define required option
parser.add_argument('--seed', required = True)
Required options are considered bad form. Use positional arguments instead.

Parse

Action Code Details
Parse system arguments using the created argparse instance
args = parser.parse_args()

Test

Action Code Details
Test if no arguments were provided
len(sys.argv) <= 1

Get

Action Code Details
Get program or script that invoked the process
sys.argv[0]
Number of arguments
len(sys.argv)