Module 22 · Lesson 59 of 64

Core revision and junior questions

Revise the whole M22 toolchain and give provable answers to junior Python interview questions, from venv and subprocess to script startup, imports and the GIL.

  • Beginner to advanced
  • 9 min read
Your place in the module
By the end you can 4 objectives
  • Recall the role of each M22 tool family, from venv and packaging to kas, BitBake and scapy
  • Answer the seven junior Python questions with a fact or command that proves each answer
  • Trace what happens from execve to bytecode execution, including sys.path, sys.modules and __pycache__
  • Explain when the GIL limits threads and why wire formats need an explicit struct byte-order prefix
Video coming soonCore revision and junior questions
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Release, handoff and self-assessment
  • A plain git push does not transfer tags: push v1.0 explicitly or use --follow-tags
  • Never move a tag others have fetched: ship a new patch version instead
  • A handoff is done when a stranger succeeds from the document alone, verified by a fresh clone
01

The module in one pass

3 min read

In the previous lesson you released devkit v1.0 with a handoff guide. This lesson revises the whole module and answers the junior questions interviewers start with, from venv versus system Python to the import system and the GIL.

The revision below is grouped the way the module was built. For each group you should be able to name the tool, say what problem it solves, and give one concrete detail that proves you used it.

Environment and packaging. A venv isolates a project's packages from the system interpreter; pyproject.toml declares the project and its dependencies; pip builds and installs from it. The provable detail: inside an activated venv, sys.executable points into the venv directory, not at /usr/bin/python3.

Host automation. pathlib replaces string concatenation for paths, subprocess.run replaces Bash glue, and logging replaces debug prints. The provable detail: subprocess.run(["ls", name]) never involves a shell, so a file name with spaces or semicolons is just data.

Board links. pyserial reads the UART, paramiko runs commands over SSH, and the socket module (with ssl for TLS) covers raw TCP. scapy belongs here too: it crafts and sniffs packets to test a device's network behaviour from the host. The provable detail: a serial read returns bytes, never str, so you decode explicitly.

Parsing and data. regex extracts fields from log lines, dataclasses hold the results, json and csv move structured data, and struct unpacks binary frames. pandas groups and cleans measurement tables; matplotlib turns them into boot charts and percentile plots. The provable detail: struct.unpack("<BH", frame) reads a little-endian byte and uint16 with no padding.

Hardware buses. gpiod requests lines from the kernel's GPIO character device, smbus2 talks to I2C sensors, spidev runs SPI transfers. The provable detail: these are permission-gated device files under /dev, and Python's timing jitter makes them fit for configuration and slow sampling, not tight control loops.

Async services. asyncio runs many waiting I/O operations in one thread; paho-mqtt publishes and subscribes telemetry; httpx calls REST APIs and FastAPI serves them. The provable detail: await yields to the event loop, so one slow board does not block the others.

Quality and build. pytest with fixtures, parametrization and hardware fakes tests the code; ruff lints and formats; mypy checks types; pre-commit runs them before each commit. On the build side, kas pins Yocto layer configuration and BitBake itself is Python: recipes embed Python functions. The provable detail: a fixture can fake a serial port so the parser is tested with no board attached.

The M22 tool familiesM22 toolingEnvironmentvenv, pip, packagingHost automationpathlib, subprocess, loggingBoard linkspyserial, paramiko, sockets, scapyParsing and datastruct, regex, JSON, pandasHardware busesgpiod, smbus2, spidevAsync servicesasyncio, MQTT, RESTQuality and buildpytest, ruff, mypy, kasM22 toolingEnvironmentvenv, pip, packagingHost automationpathlib, subprocess,loggingBoard linkspyserial, paramiko,sockets, scapyParsing and datastruct, regex, JSON, pandasHardware busesgpiod, smbus2, spidevAsync servicesasyncio, MQTT, RESTQuality and buildpytest, ruff, mypy, kas
The M22 tool families in one tree: each branch is one sentence you can defend in an interview.
Going deeperWhy struct padding matters on the wire

struct has two sizing modes. With no prefix (or @), it uses native byte order, native sizes and native alignment, and it inserts padding bytes exactly as a C compiler would. With <, >, ! or =, it uses standard sizes and no alignment at all. On this course's x86-64 and ARM64 machines:

python
import struct
struct.calcsize("BH")    # native: 4 (1 byte, 1 pad byte, 2 bytes)
struct.calcsize("<BH")   # standard little-endian: 3, no padding

In a real run on Ubuntu 24.04 with Python 3.12.3 the sizes were BH 4, @BH 4, <BH 3, >BH 3, !BH 3 and =BH 3. A firmware struct sent over UART was compiled with the target's alignment rules, which may not match your host's. If you unpack with native mode you can silently read the wrong offsets. The defensible answer: always give an explicit byte-order prefix for anything that crosses a wire, and check calcsize against the protocol document before parsing.

02

Junior questions, provable answers

4 min read

venv versus system Python? The system interpreter at /usr/bin/python3 is owned by apt, and Ubuntu 24.04 marks it externally managed (PEP 668): pip refuses to install into it and prints an externally-managed-environment error. A venv is a directory with its own site-packages and a python3 that uses the base interpreter but a private package set. Prove it:

bash
python3 -m venv .venv
source .venv/bin/activate
python3 -c "import sys; print(sys.executable, sys.prefix)"

Both paths point inside .venv. Deactivate and they point at the system locations. In a real run, the venv's python printed /tmp/s8/v1/bin/python /tmp/s8/v1 (with sys.base_prefix still /usr), while the system python printed /usr/bin/python3 /usr. The refusal is just as concrete: on Ubuntu 24.04, python3 -m pip install colorama outside a venv printed error: externally-managed-environment and This environment is externally managed, and the marker file is /usr/lib/python3.12/EXTERNALLY-MANAGED. (If venv creation fails, install the python3-venv package first.)

Do not defeat the guard

pip's --break-system-packages flag exists, and it does what it says: it lets pip overwrite files apt manages, which can break system tools that import Python. The interview-safe answer is always a venv (or pipx for installed applications), never the flag.

bytes versus str? str is a sequence of Unicode code points (text); bytes is a sequence of 8-bit values (raw octets). They never convert implicitly: b"ab" + "cd" raises TypeError: can't concat str to bytes. You cross the boundary explicitly with .encode("utf-8") and .decode("utf-8"). Serial ports, sockets and files opened in binary mode all give you bytes, which is why every board-facing parser in M22 starts with a decode or a struct.unpack.

list versus tuple? A list is mutable; a tuple is immutable after creation. A tuple of hashable items is itself hashable, so it can be a dict key or set member; a list cannot. The subtlety worth saying out loud: immutability is shallow. A tuple containing a list still lets you mutate that list; what is fixed is the tuple's own references.

argparse? The standard-library CLI parser. You declare arguments, and it generates --help, converts types with type=int, enforces required arguments, and exits with status 2 and a usage message on bad input. Prove the exit code: run a script with a missing required argument, then echo $? (a real run printed a.py: error: the following arguments are required: --port and the status was 2). This is what turned your devkit scripts into a real command-line tool.

Reading a file? Use a context manager so the file closes even on an exception, and name the encoding:

python
with open("boot.log", encoding="utf-8") as f:
    for line in f:
        process(line)

Iterating the handle reads line by line without loading the whole file, which matters for multi-megabyte boot logs. For small files, pathlib.Path("boot.log").read_text(encoding="utf-8") is the one-liner.

subprocess versus os.system? os.system(cmd) passes the whole string to /bin/sh -c, returns an encoded wait status (os.system('exit 3') returned 768, and os.waitstatus_to_exitcode(768) gives 3), and cannot capture output; anything interpolated into the string is shell code. subprocess.run with a list executes the program directly with no shell, captures output with capture_output=True, and raises CalledProcessError on failure with check=True:

python
r = subprocess.run(["ls", "-l", name], capture_output=True, text=True, check=True)

A file name like x; rm -rf y is one harmless argument here and a disaster in os.system. That contrast is the whole answer.

logging versus print? print writes to stdout and is program output. logging writes diagnostic records with levels (DEBUG to CRITICAL), timestamps and logger names, goes to stderr by default, and can be reconfigured or silenced per module without editing code. Prove the stream split: run a script that does both, redirect stdout to a file, and the log lines still appear on the terminal.

Going deepervenv versus Docker for reproducibility

A venv pins Python packages, nothing else: it shares the system interpreter, the C libraries and the whole OS with the host. Two machines with different Ubuntu releases can install the same requirements.txt and still behave differently because libc or the interpreter differs. A Docker image pins the entire userland: interpreter version, system libraries, tools, and your locked packages together. The honest answer is that they solve different layers and compose: a good CI Dockerfile creates a venv inside the image and installs from a pinned lock file. venv answers "which packages does this project use"; Docker answers "which machine does it run on".

venv and Docker isolate different layersvenvDockerIsolatesPythonpackageswholeuserlandShares with hostinterpreter,OS librarieskernel onlyPins vialockedrequirementsimage digestBest forper-projectdependenciesCI, full reproducibility
venv and Docker isolate different layers; reproducible builds usually want both.
03

Whiteboard: startup, imports and the GIL

4 min read

Start below Python. When you type python3 flash.py, the shell forks a child and calls execve on /usr/bin/python3 (see the fork(2) and execve(2) man pages). If you instead run ./flash.py directly, the kernel's execve reads the , such as #!/usr/bin/env python3, and executes that interpreter instead. Either way, a CPython process starts with your script path in its arguments.

Step by stepWhat CPython does with flash.py
  1. Initialise the runtime: interpreter state, builtins, and the import machinery come up before any of your code runs.

  2. Set sys.path: entry 0 becomes the directory containing flash.py, followed by standard library and site-packages entries.

  3. Compile the source: your file is parsed and compiled to bytecode in memory; the main script is not cached as a .pyc.

  4. Execute in main: top-level statements run in a module named __main__, which is why the if __name__ == "__main__": guard works.

  5. Import on demand: each import statement resolves a module, executes it once, and caches it.

Running python3 flash.pyfork +execveshellstartspython3Runtimeinitbuiltins,sys.pathCompilesourceto bytecodeExecute__main__Imports ondemandsys.modulescachefork +execveshellstartspython3Runtimeinitbuiltins,sys.pathCompilesourceto bytecodeExecute__main__Imports ondemandsys.modulescache
From the shell's execve to bytecode execution: the layers an interviewer expects you to name.

The import system deserves its own minute. import serial first checks . On a miss, finders search sys.path in order, the module's top-level code executes exactly once, and the result is cached. Imported modules (unlike the main script) get their bytecode cached under __pycache__ with a version-tagged file name, so the next run skips recompilation. Two provable details: with python3 tools/flash.py, sys.path[0] is tools/, not your working directory; with python3 -m devkit.cli, entry 0 is the working directory (a real run printed /tmp/s8/tools for the first and /tmp/s8 for the second, and after running a script that imports a helper, __pycache__ held only helper.cpython-312.pyc). That difference explains most "works when I run it differently" import bugs.

The GIL question usually follows. The is per-interpreter, not per-thread-state. POSIX threads (pthreads(7)) are real kernel-scheduled threads; the GIL is a userspace rule CPython adds on top. So two Python threads never execute bytecode in parallel on two cores, but the lock is released around blocking I/O: a thread waiting on serial.read() or a socket holds no GIL, and other threads run freely.

Going deeperWhy the GIL exists, and when it matters

CPython manages memory with reference counts: every assignment and scope exit increments or decrements counters, and an object dies when its count hits zero. Without the GIL, every one of those updates would need atomic operations or per-object locks, which would slow down the overwhelmingly common single-threaded case. The GIL makes refcounting cheap and C extensions simple to write. The cost lands on CPU-bound threads: two threads doing pure-Python parsing take about as long as one, sometimes longer because of lock handoffs. In a real test, one 8-million-iteration counting loop took 0.17 s and two threads each running the same loop took 0.33 s, about the sum rather than the maximum, so there was no parallel speedup (your timings will differ). The decision rule you should state: threads (or asyncio) for I/O-bound work such as serial capture plus SSH polling; multiprocessing for CPU-bound work such as crunching a large log; and note that C extensions like NumPy can release the GIL inside long numeric loops. Ubuntu 24.04's Python 3.12 always has the GIL (sysconfig.get_config_var('Py_GIL_DISABLED') printed None there); free-threaded builds are a separate CPython build option and not what runs here.

You now have the junior layer covered: every answer is a claim plus a proof you have actually run. The next lesson, "Mid-level and scenario answers", moves up a level: design trade-offs, debugging stories and board-farm scenarios where the interviewer asks what you would do, not what a function returns.

Key takeaways

  • Ubuntu 24.04 marks the system Python externally managed, so pip installs belong in a venv
  • subprocess.run with a list argument bypasses the shell; os.system always runs its string through /bin/sh
  • sys.path[0] is the script's directory, imports execute once and are cached in sys.modules
  • The GIL lets only one thread execute bytecode at a time, so threads help I/O-bound work but not CPU-bound work
Reflect
  1. Explain to a colleague, in two sentences: recall the role of each M22 tool family, from venv and packaging to kas, BitBake and scapy
  2. Which objective are you least sure about? Re-read that section.
References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close