How to Build a CLI with argparse in Python
Create a beginner-friendly command-line tool in Python that processes multiple filenames with optional flags for verbose output and uppercase conversion.
Python code
20 linesimport argparse
def main():
parser = argparse.ArgumentParser(
description="A simple CLI to process files with optional verbose mode."
)
parser.add_argument("filenames", nargs="+", help="Files to process")
parser.add_argument("-v", "--verbose", action="store_true", help="Print extra details")
parser.add_argument("-u", "--upper", action="store_true", help="Convert file names to uppercase")
args = parser.parse_args()
for filename in args.filenames:
name = filename.upper() if args.upper else filename
if args.verbose:
print(f"Processing: {name}")
else:
print(f"Done with {name}")
if __name__ == "__main__":
main()
Output
$ python cli.py file1.txt file2.csv -v -u
Processing: FILE1.TXT
Processing: FILE2.CSV
$ python cli.py doc.txt
Done with doc.txt
How it works
The argparse module is part of the Python standard library, so no extra dependencies are needed. nargs="+" gathers one or more positional arguments into a list, letting you process many files in one run. The store_true action creates boolean flags that default to False and become True when present. The namespace object from parse_args holds all arguments, and reading them with args.filename keeps the code clean and readable.
Common mistakes
- Forgetting to include `if __name__ == "__main__":` so the script runs on import.
- Using `nargs="*"` instead of `"+"` when at least one filename is required.
- Not handling the case where no filenames are passed, leading to a confusing error.
- Accessing argument attributes incorrectly, like `args.filenames` vs the defined name.
Variations
- Add `default` values to flags, e.g., `-o --output` with a default file name.
- Use `choices` to restrict possible values for an argument, like `parser.add_argument("--mode", choices=["fast", "safe"])`.
Real-world use cases
- A log aggregator script that takes multiple log file paths and outputs a processed summary.
- A file conversion utility that converts several input files and optionally prints verbose progress.
- A deployment script that takes a list of target servers and supports flags for dry-run or debug output.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.