Filters
How to search
  • Plain words find names, texts and examples.
  • "two words" finds the exact phrase.
  • --name or -x finds an option.
  • #word looks only inside commands.
  • @grep finds lessons and labs that use grep.
  • Filters: cat:network · in:labs · in:notes · level:rhcsa · ch:8 · root:yes. Put ! before a word to leave it out. OR between words means one of them.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search

Chapter 1Name in the course: 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 Lessons
  • 2 Commands

$ run as a normal user# run as root (or with 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

Commands in this lesson

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

Remember

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()

Remember

if __name__ == "__main__": runs main() only when the file is started directly — not when another script imports it.

All commands in this chapter