هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.
$ مستخدم عادي# بصلاحية root (أو مع sudo)
Run Python
Run a file, a one-liner, or the interactive shell (REPL) to try things.
python3 --version
Python 3.12.5
python3 hello.py
python3 -c 'import platform; print(platform.node())'
python3#!/usr/bin/env python3
"""Print a greeting with the host name."""
import socket
print(f"Hello from {socket.gethostname()}")chmod +x hello.py
./hello.py
Hello from server1.example.comIsolate packages with a virtual environment
A venv is a private folder of packages per project — never pip install into the system Python.
python3 -m venv .venv
source .venv/bin/activate
pip install requests pyyaml
pip freeze > requirements.txt
deactivate
python3 -m venv .venv && .venv/bin/pip install -r requirements.txtتذكّر
Add .venv/ to .gitignore; commit requirements.txt.
Use values and variables
Python has a few basic types; the type comes from the value.
host = "web1" # str
port = 443 # int
load = 0.75 # float
up = True # bool
nothing = None # no value
print(f"{host}:{port} load={load:.0%} up={up}")
print(type(port), int("8080"), str(22), float("1.5"))| Operator | Meaning |
|---|---|
+ - * / | Maths (/ always gives a float) |
//, %, ** | Whole division, rest, power |
== != < > <= >= | Compare |
and or not | Logic |
in | Contains: "err" in line |
Decide with if
Indentation (4 spaces) makes the block — no braces.
import shutil
usage = shutil.disk_usage("/")
percent = usage.used / usage.total * 100
if percent >= 90:
print(f"CRITICAL: / is {percent:.0f}% full")
elif percent >= 80:
print(f"WARNING: / is {percent:.0f}% full")
else:
print(f"OK: / is {percent:.0f}% full")Repeat with for and while
for walks over any list or file; while repeats while a condition is true.
servers = ["web1", "web2", "db1"]
for name in servers:
print(f"checking {name}")
for i, name in enumerate(servers, start=1):
print(i, name)
for n in range(3):
print("try", n)
tries = 0
while tries < 5:
tries += 1
if tries == 3:
continue
print("attempt", tries)Write functions
A function is a named, reusable block with inputs (parameters) and an output (return).
def percent(used: int, total: int, digits: int = 1) -> float:
"""Return used/total as a percentage."""
if total == 0:
return 0.0
return round(used / total * 100, digits)
def main() -> None:
print(percent(45, 60))
print(percent(1, 3, digits=3))
if __name__ == "__main__":
main()تذكّر
if __name__ == "__main__": runs main() only when the file is started directly — not when another script imports it.