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

推荐订阅源

T
The Blog of Author Tim Ferriss
S
Schneier on Security
H
Help Net Security
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MongoDB | Blog
MongoDB | Blog
云风的 BLOG
云风的 BLOG
H
Hacker News: Front Page
C
Check Point Blog
P
Privacy International News Feed
IT之家
IT之家
爱范儿
爱范儿
AWS News Blog
AWS News Blog
The Hacker News
The Hacker News
Stack Overflow Blog
Stack Overflow Blog
Project Zero
Project Zero
Microsoft Azure Blog
Microsoft Azure Blog
量子位
The Cloudflare Blog
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
I
Intezer
Martin Fowler
Martin Fowler
Scott Helme
Scott Helme
酷 壳 – CoolShell
酷 壳 – CoolShell
A
Arctic Wolf
T
Threat Research - Cisco Blogs
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
The Exploit Database - CXSecurity.com
B
Blog
Simon Willison's Weblog
Simon Willison's Weblog
U
Unit 42
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
博客园_首页
J
Java Code Geeks
K
Kaspersky official blog
Webroot Blog
Webroot Blog
C
CERT Recently Published Vulnerability Notes
H
Heimdal Security Blog
G
Google Developers Blog
T
Tor Project blog
W
WeLiveSecurity
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Blog — PlanetScale
Blog — PlanetScale
小众软件
小众软件
有赞技术团队
有赞技术团队

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
I Shipped One Messy Python Script. Here's the 10-Point Checklist That Got It There.
2-glitch · 2026-06-13 · via DEV Community

AI can generate a functional Python script in approximately ninety seconds. The script executes successfully, and the user proceeds to the next task.

However, the script often persists beyond its initial use. It may include a hard-coded Downloads path or a comment such as # edit before running!!. Subsequently, someone might duplicate it as script_v2_FINAL.py. Weeks later, a teammate may attempt to use the script with a slightly different CSV file, resulting in a raw traceback or, more problematically, the script silently producing an incomplete file and exiting with a success code.

That gap between "runs on my machine" and "I'd let someone else run this" — that distance is the actual engineering work. And AI almost never closes it for you, because you never asked. (That's an observation from watching a lot of generated coThis post provides a detailed analysis of a deliberately typical, disorganized script. I will identify each defect and demonstrate the necessary modifications to prepare it for distribution. By the conclusion, readers will have a ten-point checklist applicable to their own code, requiring only Python and pytest.on your own code today, with zero tools beyond Python and pytest.

The "before" — a script that works exactly once
The following is the initial script. It aggregates expenses from a CSV file by category and flags entries exceeding a specified limit. Although it functions as intended, this apparent success can be misleading. (The script is abbreviated for brevity; the overall structure remains representative.)

expense report script v2 FINAL (working!!)

import csv

INPUT = "/Users/me/Downloads/expenses.csv" # <- edit this before running!!
LIMIT = 500

print("starting...")

rows = []
try:
f = open(INPUT)
r = csv.reader(f)
next(r) # skip header
for row in r:
rows.append(row)
except:
print("error reading file")

for row in rows:
cat = row[1]
amt = float(row[2])
# ...total by category, flag over LIMIT, print a report...

out = open("report.txt", "w")

...write each category Identify the critical issues present in the script:, wrote report.txt")

Count the landmines:

A hardcoded home path (/Users/me/Downloads/expenses.csv) you must edit in source to use the tool.
A bare except: that swallows every error — including bugs in your own code — and then keeps running on an empty rows list.
Positional column access (row[1], row[2]) that explodes on a missing column and gives no clue which one.
float(row[2]) that crashes the whole run on one malformed cell.
print() for everything — diagnostics, results, and the "FLAGGED" lines all jammed into stdout together.
A non-atomic write (out = open("report.txt", "These issues are common and representative of typical AI-generated Python scripts. The following sections will address how to prepare such scripts for reliable distribution. --help.
None of this is exotic. This is what working AI-generated Python looks like. Let's ship it.

The checklist (run this on any script)
This is the evaluation rubric I apply before sharing code with others. Each criterion is scored from 0 to 2, for a maximum of twenty points. Apply strict standards; a 'partially' addressed item receives a score of 1. Each entry presents a Failure and corresponding Fix for efficient review.

Error handling — Failure: a bare except: (automatic 0), or raw tracebacks on bad input. Fix: wrap I/O, parsing, and network calls in specific exceptions; failures produce actionable messages and a nonzero exit code.
Secrets & config — Failure: hardcoded keys, tokens, or home paths. Fix: config comes from arguments or env. Grep your own code for api_key =, password =, token =, sk-, Bearer, and absolute home paths before you ship.
Inputs & validation — Failure: the script assumes well-formed input. Fix: check every external input — what happens on an empty file? A missing column? a path with spaces?
Logging & observability — Failure: print() for diagnostics, or total silence on failure. Fix: logging with levels; user output separated from debug noise.
Tests — Failure: none (most scripts). Fix: a pytest suite covering the happy path and at least three failure modes, with all tests running green.
Dependency hygiene — Failure: undeclared or unpinned deps, dead imports. Fix: declare dependencies with version bounds; imports match declared deps.
Interface & UX — Failure: values you edit in source to run it. Fix: a real CLI (--help, exit codes) or a documented API.
Packaging & install — Failure: "clone it and run python script.py and hope." Fix: pip install . works, an entry point is defined, it runs from any directory.
Documentation — Failure: no runnable example. Fix: a README with one-line purpose, install, a copy-pasteable example, and expected output.
Portability — Failure: open() without encoding= blows up on a non-UTF-8 file; OS-specific paths wiA critical rule for effective use of this checklist is that every finding must reference a specific file and line number. General statements such as 'improve error handling' are insufficient. Instead, precise observations like 'open() at line 14 crashes on a missing file' are required. Ambiguous findings are unlikely to be addressed.dling" is banned. "open() at line 14 crashes on a missing file" is the standard. Vague findings never get fixed.

Now the three fixes that matter most.

Fix 1: bare except → specific exceptions + real exit codes
The guiding principle is concise: always catch specific exceptions rather than broad ones, and handle exceptions at the program's boundaries rather than within core logic. Internal code should raise exceptions without handling them directly. Only the main() function should convert errors into user-facing messages and exit codes. Exit codes must be meaningful: 0 for success, 1 for runtime failure, and 2 for usage errors. Otherwise, shell pipelines and scheduled jobs that depend on the script may fail unpredictably.

Here's the validation from the shipped core.py. Notice it names the missing column instead of dying on row[1]:

class AppError(Exception):
""" Expected, user-facing failure. Message says what to do, not just what broke."""

REQUIRED_COLUMNS = ("date", "category", "amount")

def read_expenses(path: Path) -> list[dict[str, str]]:
if not path.is_file():
raise AppError(f"input file not found: {path}")
with open(path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
if reader. fieldnames is None:
raise AppError(f"{path} is empty — expected a header row")
missing = [c for c in REQUIRED_COLUMNS if c not in reader.fieldnames]
if missing:
raise AppError(f"{path} is missing required column(s): {', '.join(missing)}")
return list(reader)
A bad row no longer kills the run — it's skipped with a warning and counted. And the top of main() does the translating:

try:
rows = read_expenseImportantly, this approach catches only AppError exceptions. Unexpected exceptions are allowed to propagate, displaying a full traceback. Suppressing such errors makes diagnosis difficult, whereas explicit tracebacks provide actionable information. Avoid wrapping main() in a generic exception handler that outputs only a vague error message.aceback — because a swallowed crash is undiagnosable, while a loud one tells you exactly what to fix. Don't wrap main() in a catch-all that prints "something went wrong."

That output write also became atomic — write to a .tmp file, then rename it into place — so a crash never leaves a cA common misconception is to conflate program output with logging. If the script is intended to print a report to standard output, use print() for that purpose. Logging, which provides diagnostic information, should be directed to standard error. Mixing these streams can disrupt output redirection for users.t goes to stderr. Mix them, then run script.py > out.csv for every user.

So the "starting..." and "read N rows" lines became leveled logs to stderr, wired to a verbosity flag — quiet by default, -v for milestones, -vv for debug:

def setup_logging(verbosity: int = 0) -> None:
level = [logging.WARNING, logging.INFO, logging.DEBUG][min(verbosity, 2)]
logging.basicConfig(level=level, handlers=[logging.StreamHandler(sys.stderr)])
Maintain discipline in logging levels: detailed information for each row should be logged at the DEBUG level; summary actions such as 'wrote report.csv' should use INFO; and warnings like 'skipped 3 rows with missing amount' should use WARNING. INFO-level messages should occur only a constant number of times per execution, never within per-row loops. Additionally, use the lazy formatting style (log.debug("row %d amount=%s", i, amt)) to avoid unnecessary string formatting when the log level is not active.

Fix 3: loose script → installable, tested CLI
The hardcoded INPUT path was replaced by an argparse CLI with --help, --limit, --output, --force, -v, and --version. The loose file became a src/ layout package with a pyproject. toml declaring an entry point:

[project.scripts]
expense-report = "expense_report.cli:main"
That's what turns "clone it and run python script.py and hope" into a real command. And the pytest suite covers the happy path plus the failure modes the original couldn't survive: missing file, empty file, missing column, non-numeric amount (skipped, not fatal), and refusing to overwrite an existing report without --force.

I verified the whole chain in a fresh virtual environment before writing this:

python3 -m venv .venv && .venv/bin/pip install ".[dev]"
.venv/bin/python -m pytest # 16 passed
.venv/bin/expense-report --help
All sixteen tests pass, the installation process is clean, and the script executes correctly from any directory. Demonstrating evidence of reliability. The checklist provided is intended for your use, and the preceding example demonstrates the complete methodology. Evaluate one of your completed scripts against the ten categories, address the most critical issues first, and verify each fix by reproducing the corresponding failure. The determination of whether a script 'needs work' is subjective, but scripts with low scores in error handling, testing, and packaging should not be distributed. A low score in error handling, tests, and packaging is one you shouldn't hand to anyone yet.

If you'd rather your AI assistant enforce this loop instead of doing it by hand, I packaged the discipline as eight Claude Code skills — the scored audit (ship-check), plus harden-errors, add-logging, make-cli, add-tests, package-it, write-readme, and a release-prep gate — along with the full before/after sample project you just read through. Full disclosure: I built it, and it's a paid kit ($19) at jackiecole.gumroad.com/l/lcscdf. The checklist in this post stands on its own either way.