پاسخ کوتاه
پنج عادت خوب در اسکریپتهای سیستمی: ۱) محیط مجازی (venv یا uv) برای هر پروژه؛ ۲) `pathlib` بهجای رشته برای مسیرها؛ ۳) `subprocess.run([...], check=True)` با لیست آرگومان و بدون `shell=True` برای جلوگیری از تزریق دستور؛ ۴) timeout برای هر درخواست شبکه؛ ۵) `logging` بهجای print و ساختار `if __name__ == "__main__"` با argparse. برای زمان، `zoneinfo` و ذخیره به UTC.
محیط و فایل
ensure_ascii=False متن فارسی را خوانا ذخیره میکند. مستندات Python.
python3 -m venv .venv && . .venv/bin/activate && pip install -r requirements.txtuv venv && uv pip install httpx pyyaml # سریعتر from pathlib import Pathimport shutil, json, csvroot = Path("/var/log/app")for p in root.glob("*.log"): if p.stat().st_size > 100 * 1024**2: print(p.name)text = Path("config.json").read_text(encoding="utf-8")cfg = json.loads(text)Path("out.json").write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")shutil.copy2("a.txt", "/backup/a.txt")with open("users.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): print(row["email"])subprocess، HTTP و لاگ
سؤالات مفهومی در سؤالات مصاحبه پایتون و استفاده از API هوش مصنوعی در پایتون و AI API.
import subprocess, logging, argparse, httpxlogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")log = logging.getLogger("tool") r = subprocess.run(["df", "-h", "/"], capture_output=True, text=True, check=True)log.info(r.stdout)# بد: subprocess.run(f"rm -rf {user_input}", shell=True) resp = httpx.get("https://api.example.ir/status", timeout=10)resp.raise_for_status()data = resp.json() def main(): ap = argparse.ArgumentParser(description="Disk check") ap.add_argument("--threshold", type=int, default=90) args = ap.parse_args() ...if __name__ == "__main__": main()زمان و همزمانی
تاریخ شمسی در تاریخ شمسی در برنامهنویسی و پروفایل کارایی در پروفایل پایتون. mirror pip در mirror npm و pip.
from datetime import datetime, timezone, timedeltafrom zoneinfo import ZoneInfonow_utc = datetime.now(timezone.utc)teh = now_utc.astimezone(ZoneInfo("Asia/Tehran"))print(teh.strftime("%Y-%m-%d %H:%M"), now_utc - timedelta(days=7)) from concurrent.futures import ThreadPoolExecutorhosts = ["10.0.0.1", "10.0.0.2"]def check(h): return h, subprocess.run(["ping", "-c1", "-W1", h], capture_output=True).returncode == 0with ThreadPoolExecutor(max_workers=20) as ex: for h, ok in ex.map(check, hosts): print(h, ok) squares = {n: n*n for n in range(5)}big = [p.name for p in Path(".").iterdir() if p.is_file() and p.stat().st_size > 1e6]سوالات متداول
shell=True چرا خطرناک است؟ ورودی میتواند دستور اضافه تزریق کند.
requests یا httpx؟ هر دو؛ httpx async هم دارد.
نسخه Python؟ نسخه پشتیبانیشده فعلی؛ 2 منسوخ است.
آخرین بازبینی: آذر ۱۴۰۵ — تیم فنی هاستیفای
تصویر کاور: Joe Mabel، مجوز Public domain، از ویکیمدیا کامنز


