الفلاتر
طريقة البحث
  • الكلمات العادية تجد الأسماء والنصوص والأمثلة.
  • "كلمتان" تجد العبارة بالضبط.
  • --name أو -x تجد خيارًا.
  • #كلمة تبحث داخل الأوامر فقط.
  • @grep تجد الدروس والمعامل التي تستخدم grep.
  • الفلاتر: cat:network · in:labs · level:rhcsa · ch:8 · root:yes. ضع ! قبل كلمة لاستبعادها. OR بين الكلمات تعني إحداها.
  • ↑ ↓ للتنقل · Enter للفتح · Esc للإغلاق · / للبحث

الفصل 1الاسم في الدورة: Python basics

Write your first Python scripts

Python is the second language of every admin after Bash: easy to read, with a huge standard library, and the language of most DevOps tools and APIs. This chapter covers running Python, virtual environments, values, conditions, loops and functions.

  • 6 الدروس
  • 2 الأوامر

هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.

$ مستخدم عادي# بصلاحية root (أو مع sudo)

1.1

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
hello.py
#!/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.com

الأوامر في هذا الدرس

1.2

Isolate 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.

الأوامر في هذا الدرس

1.3

Use values and variables

Python has a few basic types; the type comes from the value.

types.py
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"))
OperatorMeaning
+ - * /Maths (/ always gives a float)
//, %, **Whole division, rest, power
== != < > <= >=Compare
and or notLogic
inContains: "err" in line

1.4

Decide with if

Indentation (4 spaces) makes the block — no braces.

check_disk.py
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")

1.5

Repeat with for and while

for walks over any list or file; while repeats while a condition is true.

loops.py
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)

1.6

Write functions

A function is a named, reusable block with inputs (parameters) and an output (return).

functions.py
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.

كل الأوامر في هذا الفصل