10 Python CLI Tools That Will Save You Hours Every Week
Repetitive tasks drain your time and energy. Python CLI automation tools let you script away the monotony and reclaim hours every week. Whether you're renaming files, processing data, or managing servers, these ten tools will transform your workflow.
What You'll Build
By the end of this guide, you'll have working knowledge of ten Python CLI tools and libraries. You'll learn to parse arguments, build beautiful terminal interfaces, and automate real-world tasks that currently eat into your productive hours.
Why Python for CLI Automation?
Python dominates CLI automation for three reasons:
-
Rich standard library —
argparse,pathlib,shutilhandle most tasks out of the box -
Third-party ecosystem — libraries like
clickandrichadd professional polish - Cross-platform — scripts work on Linux, macOS, and Windows without modification
Full Tutorial
1. argparse — Built-in Argument Parsing
argparse ships with Python and handles argument parsing without dependencies.
import argparse
import os
def main():
parser = argparse.ArgumentParser(
description="Bulk rename files in a directory"
)
parser.add_argument("directory", help="Target directory")
parser.add_argument("--prefix", default="file_", help="New prefix")
parser.add_argument("--start", type=int, default=1, help="Starting number")
parser.add_argument("--dry-run", action="store_true", help="Preview changes")
args = parser.parse_args()
files = sorted([
f for f in os.listdir(args.directory)
if os.path.isfile(os.path.join(args.directory, f))
])
for i, filename in enumerate(files, start=args.start):
ext = os.path.splitext(filename)[1]
new_name = f"{args.prefix}{i:04d}{ext}"
old_path = os.path.join(args.directory, filename)
new_path = os.path.join(args.directory, new_name)
if args.dry_run:
print(f" {filename} -> {new_name}")
else:
os.rename(old_path, new_path)
print(f"Renamed: {filename} -> {new_name}")
if __name__ == "__main__":
main()
2. click — Declarative CLI Framework
click simplifies CLI creation with decorators and automatic help generation.
import click
import subprocess
import sys
@click.group()
def cli():
"""Server management toolkit."""
pass
@cli.command()
@click.option("--port", default=8000, help="Port to run on")
@click.option("--host", default="0.0.0.0", help="Bind address")
@click.option("--workers", default=4, type=int, help="Worker count")
def start(host, port, workers):
"""Start the production server."""
click.echo(f"Starting server on {host}:{port} with {workers} workers")
cmd = f"gunicorn -w {workers} -b {host}:{port} app:app"
subprocess.run(cmd, shell=True)
@cli.command()
@click.option("--format", "fmt", default="table", type=click.Choice(["table", "json", "csv"]))
def status(fmt):
"""Check system status."""
click.echo("Checking server health...")
if fmt == "table":
click.echo(f"{'Service':<20} {'Status':<10} {'PID':<8}")
click.echo("-" * 38)
click.echo(f"{'web-server':<20} {'running':<10} {'4523':<8}")
click.echo(f"{'redis':<20} {'running':<20} {'1234':<8}")
if __name__ == "__main__":
cli()
3. rich — Beautiful Terminal Output
rich adds color, tables, progress bars, and syntax highlighting to your CLI.
from rich.console import Console
from rich.table import Table
from rich.progress import track
from rich.panel import Panel
import time
console = Console()
def show_dashboard():
table = Table(title="System Metrics", show_header=True)
table.add_column("Metric", style="cyan")
table.add_column("Value", style="green")
table.add_column("Status", style="bold")
table.add_row("CPU Usage", "34%", "[green]Normal[/green]")
table.add_row("Memory", "67%", "[yellow]Warning[/yellow]")
table.add_row("Disk", "89%", "[red]Critical[/red]")
console.print(table)
def process_items(items):
for item in track(items, description="Processing..."):
time.sleep(0.05)
console.print(Panel("Welcome to System Monitor", style="bold blue"))
show_dashboard()
process_items(range(100))
4. pathlib — Modern File Operations
from pathlib import Path
project = Path("./src")
python_files = list(project.rglob("*.py"))
total_lines = sum(len(f.read_text().splitlines()) for f in python_files)
print(f"Found {len(python_files)} files with {total_lines:,} total lines")
5. subprocess — System Command Integration
import subprocess
result = subprocess.run(
["git", "log", "--oneline", "-5"],
capture_output=True, text=True, check=True
)
for line in result.stdout.strip().split("\n"):
print(line)
6. watchdog — File System Monitoring
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
class Handler(FileSystemEventHandler):
def on_modified(self, event):
print(f"Changed: {event.src_path}")
def on_created(self, event):
print(f"Created: {event.src_path}")
observer = Observer()
observer.schedule(Handler(), path="./watch", recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
7. cookiecutter — Project Scaffolding
pip install cookiecutter
cookiecutter https://github.com/audreyr/cookiecutter-pypackage
8. fabric — Remote Execution
from fabric import Connection
def deploy():
conn = Connection("web-server.example.com")
conn.run("git pull origin main")
conn.run("pip install -r requirements.txt")
conn.run("sudo systemctl restart app")
print("Deployment complete!")
9. questionary — Interactive Prompts
import questionary
action = questionary.select(
"What do you want to do?",
choices=["Deploy", "Rollback", "View Logs", "Exit"]
).ask()
print(f"You selected: {action}")
10. typer — Modern CLI Framework
import typer
app = typer.Typer()
@app.command()
def greet(name: str, excited: bool = False):
"""Greet someone."""
msg = f"Hello, {name}!"
if excited:
msg = msg.upper() + "!!!"
typer.echo(msg)
@app.command()
def count_files(directory: str = "."):
"""Count files in directory."""
from pathlib import Path
count = len(list(Path(directory).rglob("*")))
typer.echo(f"Found {count} files")
if __name__ == "__main__":
app()
Real-World Automation Projects
Combine these tools for powerful workflows:
-
Log rotation —
pathlib+clickfor file management CLIs -
Deployment pipelines —
fabric+richfor remote server management -
Data processing —
argparse+subprocessfor ETL scripts -
Monitoring —
watchdog+richfor real-time dashboards
Performance Tips
- Use
pathliboveros.pathfor cleaner, more maintainable code - Cache expensive operations with
functools.lru_cache - Add
--quietand--verboseflags to every tool you build - Always validate inputs before processing
Get the Code
Ready to use these tools? Browse our collection of tested, production-ready Python scripts:
🔗 Browse Products: Anna's Digital Products
All products include:
- ✅ Tested and verified code
- ✅ Instant delivery via crypto or card
- ✅ Free updates forever
- ✅ Telegram bot support (@AnnaLilithBot)
Get the Production-Ready Version
Don't want to build it yourself? We have production-ready versions at https://petroleum-board-hawaii-lol.trycloudflare.com.
What you get:
- Complete, tested Python code
- Documentation and setup guides
- Instant delivery after crypto payment
- Free updates
Top comments (0)