Intermediate level · Module 5: Automating Everyday Office Tasks with Python · Lesson 4 of 4
Command-Line Options for Reusable Tools
Turn one-off scripts into reusable tools with command-line options, help text and safe defaults.
In this lesson you will
- Add command-line options to a script with argparse
- Provide help text, defaults and a dry-run flag
Key concepts
argparsecommand-line argumentflaghelp text
The lesson
A script that only works for one folder or one month must be edited every time it is used. Command-line options let the same script handle different inputs: python sort_files.py --folder Downloads --dry-run.
The argparse module in the standard library defines the options, converts their types and generates help text automatically, so colleagues can run python script.py --help to learn how to use it.
Choose safe defaults. Make destructive actions require an explicit flag, and make --dry-run easy to find, so a mistyped command cannot damage files.
Step by step
- Import argparse and create a parser with a description.
- Add --folder (required) and --dry-run (a flag).
- Use the parsed values in your file-sorting code.
- Run the script with --help and with both options.
Practice activity
Convert your file-sorting script into a tool with --folder, --dry-run and --report options, and write a one-paragraph usage note for a colleague.
Expected result: A tool that works on any folder, prints helpful usage information and changes nothing in dry-run mode.
Check your understanding
-
Why should destructive actions require an explicit flag?
Show answer
So that the safe behaviour is the default and a mistake in the command cannot delete or move files unintentionally.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.