Python

Python automation script: subprocess, pathlib và argparse

Viết script Python gọn, đúng cách: gọi lệnh shell an toàn, xử lý file, parse argument và đóng gói để chạy cron.

AO
AlexOps Notes
System & Cloud Notes9 phút03/07/2026
PythonAutomationsubprocessargparse

subprocess.run thay vì os.system

os.system trả về exit code nhưng không capture output. subprocess.run kiểm soát được stdout, stderr, timeout và raise exception khi lệnh lỗi bằng check=True.

Dùng list argument thay vì string để tránh shell injection: subprocess.run(["ls", "-la", path], check=True) thay vì subprocess.run(f"ls -la {path}", shell=True).

Bước tiếp theo

Nếu áp dụng vào dự án thật, hãy bắt đầu bằng phiên bản nhỏ nhất có thể đo được, ghi lại quyết định kỹ thuật, rồi cải tiến dựa trên log và phản hồi người dùng.

Tags: