25. Command-Line Arguments

The argparse module helps you build command-line programs that accept flags and parameters. It is the standard-library way to turn a script into a proper CLI tool.

25.1. Basic arguments

Create a parser, declare the arguments you expect, and then read them from args.

1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument('name')
5parser.add_argument('age', type=int)
6args = parser.parse_args()
7
8print(f'{args.name} is {args.age} years old.')

25.2. Flags

Boolean flags are a good fit for optional behavior such as --verbose.

 1import argparse
 2
 3parser = argparse.ArgumentParser()
 4parser.add_argument('--verbose', action='store_true')
 5args = parser.parse_args()
 6
 7if args.verbose:
 8    print('verbose mode enabled')
 9else:
10    print('verbose mode disabled')

25.3. Choices

You can restrict an argument to a small set of valid values.

1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument('mode', choices=['fast', 'safe', 'debug'])
5args = parser.parse_args()
6
7print(f'mode={args.mode}')

25.4. Exercise

Write a command-line temperature converter that accepts a numeric value and a mode of either c-to-f or f-to-c. Print the converted result.

25.4.1. Solution

 1import argparse
 2
 3parser = argparse.ArgumentParser()
 4parser.add_argument('value', type=float)
 5parser.add_argument('mode', choices=['c-to-f', 'f-to-c'])
 6args = parser.parse_args()
 7
 8if args.mode == 'c-to-f':
 9    result = args.value * 9 / 5 + 32
10else:
11    result = (args.value - 32) * 5 / 9
12
13print(result)