Python automation and practical scripting · Lesson 2 of 3
Command-line tools with argparse
Turn a script into a clear command-line application with validated options.
Lesson
1. Concept and mental model
The argparse module builds command-line interfaces from declared arguments. Give each option a clear name, type, default, and help message. Positional arguments are appropriate for required inputs such as a source file; flags are useful for optional behavior such as --dry-run. Validate values that need more than basic type conversion, and fail early with an actionable message instead of starting an operation with invalid settings.
2. How it works
Keep command-line parsing at the application boundary. Core functions should accept ordinary Python values rather than reading sys.argv themselves, which makes them reusable from tests or another module. A main() function can parse arguments, call focused functions, and return an exit status. Use nonzero exit codes for failures so shells and schedulers can detect unsuccessful jobs.
3. Use it safely and effectively
Design destructive behavior to require an explicit flag or confirmation. Print a summary of what happened, write diagnostics to standard error when appropriate, and avoid printing credentials or full private records. Test --help, missing inputs, invalid values, and representative valid calls. A command-line tool is an interface for people and automation alike, so stable argument names and predictable exit behavior matter.
4. Syntax reference
import argparse
parser = argparse.ArgumentParser(description='Summarize a CSV file')
parser.add_argument('source')
parser.add_argument('--dry-run', action='store_true')
args = parser.parse_args()
print(args.source, args.dry_run)5. Guided walkthrough
Declare each command-line argument with a meaningful name and help description, then pass parsed values into reusable functions. Test --help and invalid inputs before relying on the command from a scheduler or another script.
6. Common mistakes to avoid
- Reading sys.argv throughout the business logic, which couples the operation to the shell.
- Treating a destructive option as the default instead of requiring an explicit confirmation or flag.
Visual guide
Command-line execution
-
Step 01
Parse
Read typed options and arguments.
-
Step 02
Validate
Check paths and incompatible options.
-
Step 03
Run
Call reusable functions and return a status.
Code examples
import argparse
parser = argparse.ArgumentParser(description='Summarize a CSV file')
parser.add_argument('source')
parser.add_argument('--dry-run', action='store_true')
args = parser.parse_args()
print(args.source, args.dry_run)
Reads command-line values, such as report.csv True.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--limit', type=int, default=10)
args = parser.parse_args()
print(args.limit)
10 when run without --limit; otherwise prints the supplied integer.
import sys
def main() -> int:
print('Task completed')
return 0
if __name__ == '__main__':
sys.exit(main())
Prints Task completed and exits with status 0.
Key points
- Turn a script into a clear command-line application with validated options.
- Prefer explicit, testable behavior over hidden side effects.
- Validate assumptions at system boundaries and handle failure deliberately.
Check your understanding
Practice
Your learning progress