System Scripting Highlights Summary
Every highlight bullet from the 10 pages in this section, gathered on one page and grouped by the page it came from.
- A script has no framework request cycle - argv, env, stdio, exit code, and signals are the whole interface
- Cron and CI only read exit codes and stdout/stderr, not your intentions
- SIGTERM can be caught for graceful shutdown; SIGKILL cannot be caught at all
- Cron runs with a minimal environment, so 'works when I run it' is not the same as 'works under cron'
- Idempotency exists because retries happen at the shell, cron, or workflow layer, not inside your script
- Use if name == 'main' and argparse/typer for CLIs
- Return explicit exit codes for automation callers
- Log to stderr; reserve stdout for machine-readable output
- Prefer pathlib over os.path string joins
- Use pathlib, shutil, and tempfile to replace fragile shell scripts
- Write temp files in target directory, then atomically replace them
- Always specify UTF-8 encoding to prevent mojibake on text files
- Check for symlinks before deleting to avoid removing unexpected targets
- Use atomic rename to safely swap temporary files into final location
- Iterate glob results without materializing to avoid large memory usage
- Use subprocess.run for most commands, Popen for streaming pipelines and interactive use
- Avoid shell=True with user input to prevent shell injection attacks on untrusted data
- Set timeout on all subprocess calls to prevent hung cron jobs from becoming zombies
- Stream large stdout with Popen instead of capturing it all to memory at once
- Always log stderr on non-zero exit to capture failure context for debugging
- Use text=False for binary tools and decode output explicitly when needed
- Make Python scripts idempotent, logged, exit with meaningful codes
- Use file locks or distributed locks to prevent overlapping runs
- Set PATH, cd to project root, use absolute venv paths in crontab
- Wrap top level in try/except and mail alerts on non-zero exit
- Run APScheduler in dedicated process to avoid duplicate jobs
- Document timezone UTC vs local, set TZ in crontab if needed
- Use paramiko or Fabric to run SSH commands and copy files from Python
- RejectPolicy is safer than AutoAddPolicy for validating unknown host keys
- Set command timeouts on exec_command and connect to prevent hung SSH sessions
- Avoid shell injection by passing user input via environment variables or base64
- Use key-based auth, disable password auth, and validate host keys in production
- Upload SFTP files to temp path then move remotely to prevent corruption
- Use httpx or requests with timeouts retries and pagination
- Set timeouts on connect and read to prevent hung scripts
- Verify webhook signatures with HMAC compare_digest to prevent forged events
- Implement idempotency for webhook retries by storing processed event IDs
- Use cursor pagination for large exports as offset breaks with data shifts
- Store secrets in Authorization header not query params to prevent proxy logging
- Stream logs line by line to keep memory flat on gigabyte files
- Try JSON parse first then fall back to regex for legacy formats
- Use named regex groups and compile patterns outside loops
- Open gzip logs in text mode and process by modification time
- Avoid greedy regex on variable fields to prevent backtracking
- Parse timestamps to UTC not local time for correct aggregation
- Treat production scripts like small services with operability requirements
- JSON logging and dry-run flags enable safe production automation
- Use exit codes to signal failures for cron and CI alerting
- Implement idempotency with create-if-not-exists and checkpoint files
- Prevent concurrent runs with locks and unbounded work with batch limits
- Guard main logic behind entrypoint checks to prevent import-time side effects
- Explicit exit codes and stderr logging for cron
- No shell=True with user input
- Dry-run before first production mutation
- pathlib and UTF-8 encoding by default
Revisado por Chris St. John·Última atualização: 31 de jul. de 2026