惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MyScale Blog
MyScale Blog
爱范儿
爱范儿
The Register - Security
The Register - Security
小众软件
小众软件
D
DataBreaches.Net
雷峰网
雷峰网
S
Secure Thoughts
L
LINUX DO - 最新话题
M
MIT News - Artificial intelligence
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
F
Fortinet All Blogs
博客园 - 叶小钗
TaoSecurity Blog
TaoSecurity Blog
博客园 - Franky
aimingoo的专栏
aimingoo的专栏
S
SegmentFault 最新的问题
Hacker News: Ask HN
Hacker News: Ask HN
Help Net Security
Help Net Security
N
News and Events Feed by Topic
S
Security Affairs
The Last Watchdog
The Last Watchdog
Forbes - Security
Forbes - Security
S
Security @ Cisco Blogs
Latest news
Latest news
O
OpenAI News
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
Blog — PlanetScale
Blog — PlanetScale
Google Online Security Blog
Google Online Security Blog
S
Securelist
博客园 - 司徒正美
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
T
Threat Research - Cisco Blogs
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Palo Alto Networks Blog
T
The Blog of Author Tim Ferriss
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
AI
AI
SecWiki News
SecWiki News
G
GRAHAM CLULEY
Cloudbric
Cloudbric
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LINUX DO - 热门话题
C
Cybersecurity and Infrastructure Security Agency CISA
B
Blog RSS Feed

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Python argparse: Build CLI Tools in 10 Minutes
German Yamil · 2026-05-10 · via DEV Community

Python argparse: Build CLI Tools in 10 Minutes

🎁 Free: AI Publishing Checklist — 7 steps in Python · Full pipeline: germy5.gumroad.com/l/xhxkzz (pay what you want, min $9.99)

The Problem with sys.argv[1]

You've been there. You write a quick script, hardcode a filename, then immediately need to change it. So you reach for sys.argv:

import sys

filename = sys.argv[1]
count = int(sys.argv[2])

Enter fullscreen mode Exit fullscreen mode

This works — until it doesn't. Run it without arguments and you get an IndexError. Pass a string where you expected an integer and it crashes. There's no help text, no validation, no defaults. Anyone else who picks up your script has to read the source code to know how to run it.

argparse solves all of this. It's in the standard library, requires no installation, and turns your script into a proper CLI tool in minutes.


The Basics: ArgumentParser

Every argparse script starts with a parser:

import argparse

parser = argparse.ArgumentParser(
    description="My CLI tool — does useful things."
)
args = parser.parse_args()

Enter fullscreen mode Exit fullscreen mode

That one call to parse_args() handles everything: reading sys.argv, validating inputs, and printing help when the user passes --help.

Positional Arguments

Positional arguments are required and identified by position, not name:

parser.add_argument("filename", help="Path to the input file")
parser.add_argument("count", help="Number of items to process")

Enter fullscreen mode Exit fullscreen mode

Optional Arguments (--flag and -f)

Optional arguments use -- prefix and can have short aliases:

parser.add_argument("--output", "-o", help="Output file path", default="output.txt")
parser.add_argument("--verbose", "-v", help="Enable verbose logging", action="store_true")

Enter fullscreen mode Exit fullscreen mode


Type Validation: No More Manual Casting

Instead of int(sys.argv[1]) wrapped in a try/except, let argparse handle it:

parser.add_argument("--count", type=int, default=10, help="Number of items")
parser.add_argument("--rate", type=float, default=1.5, help="Processing rate")
parser.add_argument(
    "--format",
    choices=["json", "csv", "txt"],
    default="json",
    help="Output format"
)

Enter fullscreen mode Exit fullscreen mode

If a user passes --count hello, argparse prints a clean error message and exits — no stack trace, no confusion.


Required Arguments, nargs, and Lists

Required Optional Arguments

parser.add_argument("--title", required=True, help="Article title (required)")

Enter fullscreen mode Exit fullscreen mode

Accepting Multiple Values

# One or more values: --tags python beginner tutorial
parser.add_argument("--tags", nargs="+", help="One or more tags")

# Zero or more values: --tags (empty is fine)
parser.add_argument("--tags", nargs="*", help="Zero or more tags")

Enter fullscreen mode Exit fullscreen mode

The result is a Python list you can iterate directly:

args = parser.parse_args()
for tag in args.tags:
    print(tag)

Enter fullscreen mode Exit fullscreen mode


Boolean Flags: store_true and store_false

Boolean flags don't take a value — their presence or absence is the value:

parser.add_argument("--dry-run", action="store_true", help="Simulate without writing")
parser.add_argument("--no-color", action="store_false", dest="color", help="Disable color output")

Enter fullscreen mode Exit fullscreen mode

Usage:

python publish.py --dry-run        # args.dry_run is True
python publish.py                  # args.dry_run is False
python publish.py --no-color       # args.color is False

Enter fullscreen mode Exit fullscreen mode


Subcommands: One Tool, Many Commands

Real CLI tools like git, docker, and pip use subcommands. add_subparsers() gives you the same structure.

parser = argparse.ArgumentParser(description="Publish queue manager")
subparsers = parser.add_subparsers(dest="command", required=True)

# `publish` subcommand
publish_parser = subparsers.add_parser("publish", help="Publish the next article in queue")
publish_parser.add_argument("--dry-run", action="store_true", help="Simulate without publishing")

# `list` subcommand
list_parser = subparsers.add_parser("list", help="Show the publish queue")
list_parser.add_argument("--format", choices=["table", "json"], default="table")

Enter fullscreen mode Exit fullscreen mode

Now args.command tells you which subcommand was chosen, and each subcommand has its own arguments.


The --verbose / -v Pattern

A common pattern is using --verbose to set the logging level at runtime:

import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument("--verbose", "-v", action="store_true", help="Enable debug logging")
args = parser.parse_args()

logging.basicConfig(
    level=logging.DEBUG if args.verbose else logging.INFO,
    format="%(levelname)s: %(message)s"
)

log = logging.getLogger(__name__)
log.info("Starting...")
log.debug("This only shows with --verbose")

Enter fullscreen mode Exit fullscreen mode


Complete Example: Publish Queue CLI

Here's a working CLI for managing an article publish queue — the same pattern used in the full pipeline.

#!/usr/bin/env python3
"""
publish_queue.py — CLI for managing the article publish queue.
Usage: python publish_queue.py <command> [options]
"""

import argparse
import json
import logging
import sys
from pathlib import Path

QUEUE_FILE = Path("queue.json")


def load_queue() -> list[dict]:
    if not QUEUE_FILE.exists():
        return []
    return json.loads(QUEUE_FILE.read_text())


def save_queue(queue: list[dict]) -> None:
    QUEUE_FILE.write_text(json.dumps(queue, indent=2))


def cmd_list(args: argparse.Namespace) -> None:
    queue = load_queue()
    if not queue:
        print("Queue is empty.")
        return
    for i, article in enumerate(queue, 1):
        status = "[published]" if article.get("published") else "[pending]  "
        print(f"{i}. {status} {article['title']} ({', '.join(article.get('tags', []))})")


def cmd_add(args: argparse.Namespace) -> None:
    queue = load_queue()
    article = {
        "title": args.title,
        "tags": args.tags or [],
        "published": False,
    }
    queue.append(article)
    save_queue(queue)
    logging.info("Added: %s", args.title)
    print(f"Added '{args.title}' to queue. Total: {len(queue)} articles.")


def cmd_publish(args: argparse.Namespace) -> None:
    queue = load_queue()
    pending = [a for a in queue if not a.get("published")]
    if not pending:
        print("No pending articles.")
        return
    next_article = pending[0]
    if args.dry_run:
        print(f"[DRY RUN] Would publish: {next_article['title']}")
        return
    next_article["published"] = True
    save_queue(queue)
    print(f"Published: {next_article['title']}")
    logging.info("Published: %s", next_article["title"])


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="publish_queue",
        description="Manage your article publish queue.",
    )
    parser.add_argument(
        "--verbose", "-v",
        action="store_true",
        help="Enable debug logging",
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    # list
    list_parser = subparsers.add_parser("list", help="Show the publish queue")
    list_parser.set_defaults(func=cmd_list)

    # add
    add_parser = subparsers.add_parser("add", help="Add an article to the queue")
    add_parser.add_argument("--title", required=True, help="Article title")
    add_parser.add_argument("--tags", nargs="*", help="Tags for the article")
    add_parser.set_defaults(func=cmd_add)

    # publish
    publish_parser = subparsers.add_parser("publish", help="Publish the next pending article")
    publish_parser.add_argument("--dry-run", action="store_true", help="Simulate without writing")
    publish_parser.set_defaults(func=cmd_publish)

    return parser


def main() -> None:
    parser = build_parser()
    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(levelname)s: %(message)s",
    )

    args.func(args)


if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

--help Output

$ python publish_queue.py --help
usage: publish_queue [-h] [--verbose] {list,add,publish} ...

Manage your article publish queue.

positional arguments:
  {list,add,publish}
    list              Show the publish queue
    add               Add an article to the queue
    publish           Publish the next pending article

options:
  -h, --help          show this help message and exit
  --verbose, -v       Enable debug logging

$ python publish_queue.py add --help
usage: publish_queue add [-h] --title TITLE [--tags [TAGS ...]]

options:
  -h, --help           show this help message and exit
  --title TITLE        Article title
  --tags [TAGS ...]    Tags for the article

Enter fullscreen mode Exit fullscreen mode

Running It

# Add articles to the queue
python publish_queue.py add --title "Python argparse guide" --tags python beginners tutorial
python publish_queue.py add --title "Automate your workflow" --tags python automation

# List the queue
python publish_queue.py list
# 1. [pending]   Python argparse guide (python, beginners, tutorial)
# 2. [pending]   Automate your workflow (python, automation)

# Publish next (dry run first)
python publish_queue.py publish --dry-run
# [DRY RUN] Would publish: Python argparse guide

python publish_queue.py publish
# Published: Python argparse guide

# Check updated queue with debug logging
python publish_queue.py list --verbose

Enter fullscreen mode Exit fullscreen mode


Key Patterns to Remember

Pattern When to use it
type=int / type=float Any numeric input
choices=[...] Fixed set of valid values
required=True Mandatory optional args
nargs="+" / nargs="*" Lists of values
action="store_true" Boolean flags
add_subparsers() Multi-command tools
set_defaults(func=...) Dispatch to subcommand functions

What You Get for Free

Every argparse-based script automatically has:

  • --help / -h — generated from your help= strings
  • Type validation — with clear error messages, no tracebacks
  • Default values — documented in the help output
  • Usage line — auto-generated from your argument definitions

No third-party libraries. No pip install. Just the standard library.


The publish queue CLI in the full pipeline uses argparse for --list, --add, and --publish: germy5.gumroad.com/l/xhxkzz — pay what you want, min $9.99.


Further Reading