Python Tutorial / Build Command-Line Programs with argparse
argparse defines command-line parameters, conversion, defaults and allowed choices, then produces help and usage errors. Keep argument parsing separate from calculations so the underlying behavior stays reusable.
Distinguish positional arguments and options
Positional arguments bind through command order; options such as --currency are named. nargs="+" requires one or more values, type selects a converter and choices restricts accepted options.
Command-line arguments may appear in shell history and process listings. Keep passwords and tokens in a suitable separate input or secret-management mechanism. Quote paths containing spaces so the shell passes them as one argument.
For the relevant APIs and platform requirements, see Build Command-Line Programs with argparse documentation.
Run a complete total command
Save this as sum_cli.py and run python sum_cli.py 3500 8000 2500 in the project environment:
import argparse
def nonnegative(text):
try:
value = int(text)
except ValueError as error:
raise argparse.ArgumentTypeError("expected an integer") from error
if value < 0:
raise argparse.ArgumentTypeError("expected a nonnegative amount")
return value
def main():
parser = argparse.ArgumentParser(description="Sum expense amounts")
parser.add_argument("amounts", type=nonnegative, nargs="+")
parser.add_argument("--currency", choices=["KRW", "USD"], default="KRW")
args = parser.parse_args()
print(f"{sum(args.amounts):,} {args.currency}")
if __name__ == "__main__":
main()
Expected output:
14,000 KRW
Inspect help, validation and exit codes
python sum_cli.py --help python sum_cli.py 0 500 --currency KRW
The second command prints 500 KRW. --currency EUR fails the choices check. Negative and nonnumeric amounts cause nonnegative to supply an explanatory argument error. Ordinary argparse usage errors exit with code 2, letting another program distinguish failure.
Run --help without supplying amounts and inspect the generated usage. Help output can include different executable paths or formatting, so checks should target its meaning rather than assume identical character-for-character output everywhere.
Extend the interface without coupling the calculation
For several operations, subparsers can organize commands such as init, add and list. Pass needed values into calculation functions rather than making them depend directly on an argparse Namespace.
- Test zero and confirm it is accepted.
- Test a negative amount, missing arguments and an invalid currency.
- Inspect each exit status and restore valid arguments.
The final expense manager combines subcommands, validation and persistent data. Each added command should retain a clear input contract and an unambiguous failure result.




