CLI Usage in Python: Basics and Best Practices
Command Line Interface (CLI) refers to interacting with programs via a terminal or shell (e.g., Command Prompt on Windows, Terminal on macOS/Linux). In Python, CLI usage is essential for running scripts, managing packages, and building user-friendly tools that accept inputs like flags or arguments without a GUI. It's efficient for automation, scripting, and server-side apps.Python's standard library supports CLI via modules like sys (for basic args) and argparse (for advanced parsing). Third-party libs like click or typer simplify complex CLIs.Why Use CLI?
Handling CLI ArgumentsRun in activated venv: python cli_tool.py input.txt -u (uppercases and prints).Tips
- Portability: Runs anywhere with a terminal.
- Automation: Integrate with scripts, cron jobs, or pipelines.
- Simplicity: No need for web/GUI frameworks.
Command | Description | Example |
|---|---|---|
python script.py | Run a Python script. | python hello.py |
python -m module | Run as module (e.g., for tools). | python -m venv myenv |
python -c "code" | Execute inline code. | python -c "print('Hi')" |
pip install pkg | Install packages (in venv!). | pip install requests |
python -m pip freeze > req.txt | Export requirements. | Saves deps to file |
- Basic: Using sys.argv
Access command-line args as a list (sys.argv[0] is script name).Run: python script.py Alice → Outputs "Hello, Alice!"pythonimport sys if len(sys.argv) > 1: name = sys.argv[1] # First arg print(f"Hello, {name}!") else: print("Usage: python script.py <name>") - Advanced: Using argparse
Built-in for flags, options, help text, and validation.Run:pythonimport argparse parser = argparse.ArgumentParser(description="Greet someone") parser.add_argument("name", help="Person's name") parser.add_argument("-g", "--greeting", default="Hello", help="Custom greeting") args = parser.parse_args() print(f"{args.greeting}, {args.name}!")- python script.py Alice → "Hello, Alice!"
- python script.py Alice -g Hi → "Hi, Alice!"
- python script.py -h → Shows help.
python
# cli_tool.py - Reads a file and outputs uppercase version
import argparse
import sys
parser = argparse.ArgumentParser(description="Process text files")
parser.add_argument("input_file", help="Input file path")
parser.add_argument("output_file", nargs="?", default=None, help="Output file (optional)")
parser.add_argument("-u", "--upper", action="store_true", help="Convert to uppercase")
args = parser.parse_args()
try:
with open(args.input_file, 'r') as infile:
data = infile.read()
if args.upper:
data = data.upper()
if args.output_file:
with open(args.output_file, 'w') as outfile:
outfile.write(data)
print(f"Written to {args.output_file}")
else:
print(data) # Output to console
except FileNotFoundError:
print(f"Error: {args.input_file} not found", file=sys.stderr)- Error Handling: Use sys.exit(1) for failures; check argparse for auto-help.
- Shebang: Add #!/usr/bin/env python at script top for direct execution (chmod +x script.py; ./script.py).
- Testing: Use python -m unittest for CLI tests.
- Advanced: Try click for decorators: pip install click, then @click.command().