Platform Engineering · Lesson 29

Finding the Right Command, Library and Method

Nobody remembers every command, module, and method. What experienced engineers have is a way of finding them: describe the job, ask the machine (man -k, --help, help(), dir()), check whether Python already has it built in, read how to call it, and notice when an answer is the old way (os.system where subprocess.run belongs). This lesson follows one beginner who needs to check disk space on servers from a script, and shows the two ways the search goes wrong: copying a legacy answer, and installing a look-alike package.

Difficulty: Beginner · Know this first: Lesson 02, Lesson 28

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from "I need to" to working code. It is a worked example, not a measurement. The legacy and third-party hops are where a search goes wrong.

Try it: which tool for the job?

Pick a job and where you take the answer from. See what you end up using.

os.popen("df -h")what you use
yesbuilt in?

Legacy: parsing df text breaks on long names and other languages

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Finding the right tool grows in four levels: asking the machine, reading the documentation well, choosing packages safely, and building habits a team can share.

Basic — Ask the machine

At the basic level you know where help lives.

  • Shell: man -k, whatis, --help, man, type, help.
  • Python: type(), dir(), help(), python3 -m pydoc.

Where it breaks: searching the web before asking the machine, and getting an answer for a different version or system.

Try it: Basic

You forgot the command that counts lines in a file. What do you type?

Now do it: Find the command that sorts lines, using only man -k.

Intermediate — Read the documentation well

At the intermediate level you read signatures, return values, and version notes.

  • inspect.signature(), the "Return" part of help(), and the module page on docs.python.org.
  • "New in version", "Changed in version", and "Deprecated since" notes; python3 -W default shows deprecation warnings.
  • Legacy to modern: os.system to subprocess.run, os.path to pathlib, optparse to argparse.

Try it: Intermediate

Your script uses datetime.datetime.utcnow() and works. Why change it?

Now do it: Run one of your scripts with -W default and fix every warning.

Advanced — Choose packages safely

At the advanced level you vet what you install.

  • Copy names from official docs; check the release history, maintainers, licence, and source on PyPI.
  • Install into a virtual environment; pin versions; pip show and pip index versions.
  • pip-audit for known vulnerabilities; an internal mirror or allowlist for production.

Try it: Advanced

Two packages with almost the same name appear in a search. Which do you install?

Now do it: For each package you use, find the official docs page that names it.

Master — Habits a team can share

At the master level the search is shared, not repeated.

  • A team list of approved packages and the standard-library modules to prefer.
  • Lint rules that flag legacy calls (os.system, shell=True, yaml.load).
  • Dependency updates by a bot, with tests, so pins do not rot.

Trade-off: an allowlist slows down trying new packages, and stops a look-alike reaching production.

Try it: Master

Three teams wrote their own disk-check helpers, two with os.popen. What helps most?

Now do it: Add a lint rule (ruff has rules for these) that flags os.system and shell=True.

Go deeper

A helper that answers the four questions for any name, using only Python itself.

import importlib, inspect, sys, warnings

def explain(dotted):
    top = dotted.split(".")[0]
    print(f"{dotted}: built in = {top in sys.stdlib_module_names}")
    try:
        obj = importlib.import_module(top)
        for part in dotted.split(".")[1:]:
            obj = getattr(obj, part)
    except (ImportError, AttributeError) as e:
        print(f"  not available here: {e}")
        return
    try:
        print(f"  call it as: {dotted}{inspect.signature(obj)}")
    except (TypeError, ValueError):
        print(f"  public names: {[n for n in dir(obj) if not n.startswith('_')][:8]}")
    doc = (obj.__doc__ or "").strip().splitlines()
    print(f"  what it does: {doc[0] if doc else '(no documentation)'}")

warnings.simplefilter("default")       # show DeprecationWarnings for the old ways
for name in sys.argv[1:] or ["shutil.disk_usage", "subprocess.run", "os.system", "yaml"]:
    explain(name)

Legacy and modern ways you will meet in old answers:

Old wayCurrent wayWhy
os.system, os.popen, commandssubprocess.run([...], capture_output=True, text=True)output, errors, and exit code; no shell
os.path.join, glob.globpathlib.Pathpaths as objects
optparse, getoptargparsehelp, types, and sub-commands built in
urllib2 (Python 2)urllib.request, or requestsrenamed in Python 3
"%s" % x, "{}".format(x)f-stringsshorter, clearer
datetime.utcnow()datetime.now(datetime.UTC)deprecated; the new one knows its timezone
time.time() for durationstime.monotonic()never jumps when the clock is set
imp, distutilsimportlib, setuptoolsremoved in Python 3.12
yaml.load(f)yaml.safe_load(f)the old one can run code from the file
logging.warnlogging.warningdeprecated spelling

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A package one letter off a popular name was installed in CI.

Timeline

  • Day 0A developer needs to parse a date format, finds a blog post, and copies its pip install line into the CI requirements. The name is one letter off a popular package.
  • Day 0, +10 minThe package's install script reads the environment, including a deploy token, and sends it to an outside server. The build passes: the package also contains a working copy of the real code.
  • Day 2The cloud provider's audit log shows calls from an unknown network using the deploy token. Tokens are rotated and the package is reported to PyPI, which removes it.

What changed after

CI installs only from an internal mirror with an allowlist, package names are copied from official documentation, pip-audit runs on every change, and deploy tokens are short-lived.

Python, example by example

How to find the right module, function, and method on your own: search by name and by meaning, read signatures and return values, spot the old ways, tell what is built in from what needs pip, and check what your Python version has. Each example is a whole program: save it under the name in its first line, run it with python3, and you should see exactly the output below it.

Find it yourself

In everyday terms

The standard library is a library building with a catalogue. sys.stdlib_module_names is the catalogue of every book on the shelves, and searching it for a word is the quickest way to the right shelf.

Start with the word for your job and search the catalogue of built-in modules. Four questions find almost anything: is it built in (sys.stdlib_module_names), what is inside (dir()), how do I call it (inspect.signature()), and what does it do (the first line of __doc__, or help() for the whole page). The examples below take each question one step at a time.

# find_it.py
import sys
for word in ("zip", "http", "json", "mail", "time"):
    found = sorted(m for m in sys.stdlib_module_names if word in m and not m.startswith("_"))
    print(f"{word:<5} {found}")
$ python3 find_it.py
zip   ['gzip', 'zipapp', 'zipfile', 'zipimport']
http  ['http']
json  ['json']
mail  ['email', 'mailbox']
time  ['datetime', 'time', 'timeit']

1. Ask an object about itself

help() prints the same page that pydoc.render_doc returns as text; the first lines say what the thing is and how to call it.

# example_01.py
import pydoc
text = pydoc.render_doc(len, renderer=pydoc.plaintext)
print("\n".join(text.splitlines()[:4]))
print(type(len), callable(len))
$ python3 example_01.py
Python Library Documentation: built-in function len in module builtins

len(obj, /)
    Return the number of items in a container.
<class 'builtin_function_or_method'> True

2. Search a module or type for a word

A three-line helper finds methods by part of their name, which is how most searches start.

# example_02.py
import pathlib, shutil

def find(obj, *words):
    return [n for n in dir(obj) if not n.startswith("_") and any(w in n for w in words)]

print(find(str, "strip"))
print(find(pathlib.Path, "exist", "mkdir"))
print(find(shutil, "copy", "disk"))
$ python3 example_02.py
['lstrip', 'rstrip', 'strip']
['exists', 'mkdir']
['copy', 'copy2', 'copyfile', 'copyfileobj', 'copymode', 'copystat', 'copytree', 'disk_usage']

3. Search by meaning: read the summaries

When you know the idea ("compress") but not the module, read the first documentation line of the likely ones.

# example_03.py
import importlib
for name in ["zipfile", "tarfile", "gzip", "bz2", "lzma", "shutil", "csv"]:
    doc = (importlib.import_module(name).__doc__ or "").strip().splitlines()
    print(f"{name:<8} {doc[0] if doc else ''}")
$ python3 example_03.py
zipfile  Read and write ZIP files.
tarfile  Read from and write to tar format archives.
gzip     Functions that read and write gzipped files.
bz2      Interface to the libbzip2 compression library.
lzma     Interface to the liblzma compression library.
shutil   Utility functions for copying and archiving files and directory trees.
csv      CSV parsing and writing.

4. Arguments, defaults, and what comes back

inspect.signature lists every argument with its default; the return value's own fields tell you what you get.

# example_04.py
import inspect, shutil
for name, p in inspect.signature(shutil.copytree).parameters.items():
    d = p.default
    default = "" if d is inspect.Parameter.empty else f" = {d.__name__ if callable(d) else repr(d)}"
    print(f"  {name}{default}")
usage = shutil.disk_usage("/")
print(type(usage).__name__, usage._fields)
$ python3 example_04.py
  src
  dst
  symlinks = False
  ignore = None
  copy_function = copy2
  ignore_dangling_symlinks = False
  dirs_exist_ok = False
usage ('total', 'used', 'free')

5. Old way, new way, same job

The old ways still run, which is why old answers look fine. Compare what each one gives you.

# example_05.py
import os, os.path, pathlib, subprocess
print(os.path.join("logs", "app.log") == str(pathlib.Path("logs") / "app.log"))
print(os.path.basename("/var/log/app.log"), "|", pathlib.Path("/var/log/app.log").name)
print("%s has %d errors" % ("web-1", 3), "|", f"{'web-1'} has {3} errors")
status = os.system("exit 0")
r = subprocess.run(["sh", "-c", "echo hi; exit 0"], capture_output=True, text=True)
print("os.system gave", status, "| subprocess.run gave", r.returncode, repr(r.stdout))
$ python3 example_05.py
True
app.log | app.log
web-1 has 3 errors | web-1 has 3 errors
os.system gave 0 | subprocess.run gave 0 'hi\n'

6. Let Python tell you it is old

Deprecated calls raise a DeprecationWarning that is hidden by default. Catch them, or run with python3 -W default, and read the advice in the message.

# example_06.py
import datetime, logging, warnings
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    datetime.datetime.utcnow()
    datetime.datetime.utcfromtimestamp(0)
    logging.getLogger("demo").warn("old spelling")
for w in caught:
    msg = str(w.message)
    advice = "Use " + msg.split("Use ")[-1] if "Use " in msg else msg
    print(w.category.__name__, "|", advice)
$ python3 example_06.py
DeprecationWarning | Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
DeprecationWarning | Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.fromtimestamp(timestamp, datetime.UTC).
DeprecationWarning | The 'warn' method is deprecated, use 'warning' instead

7. Built in, or from PyPI?

sys.stdlib_module_names knows every built-in module. For the rest, the install name can differ from the import name: look it up once and write it down.

# example_07.py
import sys
INSTALL = {"yaml": "pyyaml", "sklearn": "scikit-learn", "dotenv": "python-dotenv", "PIL": "pillow", "requests": "requests"}
for name in ["json", "tomllib", "yaml", "sklearn", "dotenv", "PIL", "requests"]:
    if name in sys.stdlib_module_names:
        print(f"import {name:<9} built in")
    else:
        print(f"import {name:<9} pip install {INSTALL[name]}")
$ python3 example_07.py
import json      built in
import tomllib   built in
import yaml      pip install pyyaml
import sklearn   pip install scikit-learn
import dotenv    pip install python-dotenv
import PIL       pip install pillow
import requests  pip install requests

8. Does this Python have it?

Features arrive in new versions. Check the version, or check for the feature itself with hasattr, before relying on it.

# example_08.py
import datetime, importlib.util, itertools, sys
print("3.11 or later:", sys.version_info >= (3, 11))
print("datetime.UTC (3.11+):", hasattr(datetime, "UTC"))
print("itertools.batched (3.12+):", hasattr(itertools, "batched"))
print("tomllib (3.11+):", importlib.util.find_spec("tomllib") is not None)
$ python3 example_08.py
3.11 or later: True
datetime.UTC (3.11+): True
itertools.batched (3.12+): True
tomllib (3.11+): True

9. Where does it live?

Every module knows its file and every function its module, so you can open the source when the documentation is not enough.

# example_09.py
import inspect, json, shutil
print("/".join(json.__file__.split("/")[-2:]))
print(inspect.getsourcefile(shutil).split("/")[-1])
print(inspect.getmodule(shutil.disk_usage).__name__)
$ python3 example_09.py
json/__init__.py
shutil.py
shutil

Practice: write the program yourself

Write each one from scratch before you open the solution. The output under each solution is what it really prints.

  1. Print the names in the string module that start with ascii, and the value of string.digits.

    Show a solution
    # task_1.py
    import string
    print([n for n in dir(string) if n.startswith("ascii")])
    print(string.digits)
    $ python3 task_1.py
    ['ascii_letters', 'ascii_lowercase', 'ascii_uppercase']
    0123456789
  2. Print the signature of json.dump and the first line of its documentation.

    Show a solution
    # task_2.py
    import inspect, json
    print(inspect.signature(json.dump))
    print(" ".join(json.dump.__doc__.split()).split(". ")[0])
    $ python3 task_2.py
    (obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
    Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object)
  3. Decide whether tomllib, toml, and zoneinfo are built in; for the ones that are, print the first few public names they offer.

    Show a solution
    # task_3.py
    import importlib, sys
    for name in ["tomllib", "toml", "zoneinfo"]:
        if name in sys.stdlib_module_names:
            module = importlib.import_module(name)
            print(f"{name}: built in, offers {[n for n in dir(module) if not n.startswith('_')][:4]}")
        else:
            print(f"{name}: not built in")
    $ python3 task_3.py
    tomllib: built in, offers ['TOMLDecodeError', 'load', 'loads']
    toml: not built in
    zoneinfo: built in, offers ['InvalidTZPathWarning', 'TZPATH', 'ZoneInfo', 'ZoneInfoNotFoundError']
  4. Catch the warning from datetime.datetime.utcfromtimestamp(0) and print its category and the replacement it suggests.

    Show a solution
    # task_4.py
    import datetime, warnings
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        datetime.datetime.utcfromtimestamp(0)
    w = caught[0]
    print(w.category.__name__)
    print("Use " + str(w.message).split("Use ")[-1])
    $ python3 task_4.py
    DeprecationWarning
    Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.fromtimestamp(timestamp, datetime.UTC).

Try it yourself, from scratch

You need Python 3 on Linux, macOS, or WSL on Windows (run wsl --install in PowerShell once); check with python3 --version. The terminal is only for setting Python up and running it and its tools: the Python itself goes in .py files, in part 2 and in "Python, example by example" above.

1. Terminal: set up and run

Type each one, read what it prints, and compare it with the note above it.

  1. Make a folder for this lesson with its own virtual environment, and install what the lesson needs into it. Every command after this runs inside it; deactivate leaves it, and source .venv/bin/activate brings it back.

    mkdir -p ~/labs/finding-the-right-library-and-method && cd ~/labs/finding-the-right-library-and-method
    python3 -m venv .venv || echo "No venv module: on Debian or Ubuntu run  sudo apt install -y python3-venv  and try again"
    source .venv/bin/activate && python --version
    pip install requests
  2. Describe the job, then search the manuals by meaning and read one-line summaries.

    man -k "space usage" | head -n 5
    whatis df du
  3. Search the standard library by topic: pydoc -k reads every module's summary (it takes a few seconds).

    python3 -m pydoc -k archive 2>/dev/null | head -n 6
  4. Read how to call the function you found, without leaving the terminal.

    python3 -m pydoc shutil.disk_usage | head -n 12
  5. Try it small, then compare it with df.

    python3 -c "import shutil; print(shutil.disk_usage('/'))"
    df -B1 / | tail -n 1
  6. See the deprecation warnings Python hides by default; each one names the new way.

    python3 -W default -c "import datetime; datetime.datetime.utcnow()"
  7. Check a package before you rely on it: its releases on PyPI, then what the installed one is and needs.

    pip index versions requests 2>/dev/null | head -n 1
    pip show requests | grep -E "^(Name|Version|Requires)"

2. Python: explain.py

This program answers the four questions for any name, using only Python itself: is it built in, can it be imported here, how is it called, and what does it do. It also flags the old ways and names the current one. Save it as explain.py in the lesson folder, then run it.

# explain.py
import importlib, inspect, sys

LEGACY = {
    "os.system": "subprocess.run([...], capture_output=True, text=True)",
    "os.popen": "subprocess.run([...], capture_output=True, text=True)",
    "datetime.datetime.utcnow": "an aware time, now(datetime.UTC)",
    "optparse.OptionParser": "argparse.ArgumentParser",
}

def explain(dotted):
    top = dotted.split(".")[0]
    if top not in sys.stdlib_module_names:
        print(f"{dotted}: not built in; find its install name in the project's docs, then pip install it")
        return
    obj = importlib.import_module(top)
    for part in dotted.split(".")[1:]:
        obj = getattr(obj, part)
    try:
        call = f"{dotted}{inspect.signature(obj)}"
    except (TypeError, ValueError):
        call = f"{dotted}(...)"
    doc = (obj.__doc__ or "").strip().splitlines()
    print(call)
    print(f"    {doc[0] if doc else '(no documentation)'}")
    if dotted in LEGACY:
        print(f"    LEGACY: use {LEGACY[dotted]}")

for name in ["shutil.disk_usage", "os.system", "subprocess.run", "datetime.datetime.utcnow", "yaml", "requests"]:
    explain(name)

Run it, and you should see this output:

$ python3 explain.py
shutil.disk_usage(path)
    Return disk usage statistics about the given path.
os.system(command)
    Execute the command in a subshell.
    LEGACY: use subprocess.run([...], capture_output=True, text=True)
subprocess.run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs)
    Run command with arguments and return a CompletedProcess instance.
datetime.datetime.utcnow()
    Return a new datetime representing UTC day and time.
    LEGACY: use an aware time, now(datetime.UTC)
yaml: not built in; find its install name in the project's docs, then pip install it
requests: not built in; find its install name in the project's docs, then pip install it

3. What to notice

4. Advanced: a test that keeps the program honest

A program you keep needs a test, so you know at once when a change alters what it does. This one uses unittest, which comes with Python: it runs explain.py and checks that it exits cleanly and prints exactly the output above. Save it as test_explain.py next to the program.

# test_explain.py: checks that explain.py still prints exactly what this lesson shows.
# Run it with:  python3 -m unittest -v test_explain
import subprocess
import sys
import unittest
from pathlib import Path

HERE = Path(__file__).resolve().parent
EXPECTED = r"""
shutil.disk_usage(path)
    Return disk usage statistics about the given path.
os.system(command)
    Execute the command in a subshell.
    LEGACY: use subprocess.run([...], capture_output=True, text=True)
subprocess.run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs)
    Run command with arguments and return a CompletedProcess instance.
datetime.datetime.utcnow()
    Return a new datetime representing UTC day and time.
    LEGACY: use an aware time, now(datetime.UTC)
yaml: not built in; find its install name in the project's docs, then pip install it
requests: not built in; find its install name in the project's docs, then pip install it
""".strip("\n")


class TestExplain(unittest.TestCase):
    def run_program(self):
        return subprocess.run([sys.executable, str(HERE / "explain.py")], cwd=HERE,
                              capture_output=True, text=True, timeout=60)

    def test_exits_cleanly(self):
        result = self.run_program()
        self.assertEqual(result.returncode, 0, result.stderr)

    def test_prints_the_expected_output(self):
        result = self.run_program()
        self.assertEqual(result.stdout.rstrip(), EXPECTED)


if __name__ == "__main__":
    unittest.main()

Run it: you should see both tests end in ok, then OK. Then change one value in the program, run it again, and read how the failure shows you the difference. pytest runs the same file unchanged, if you prefer it.

python3 -m unittest -v test_explain

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your team needs a script that checks the TLS certificate expiry of 200 hostnames every morning and posts a summary to chat. Before writing any code, find the tools.

Clarifying questions to ask

Which standard-library modules open a TLS connection and read a certificate? How do you find out what they return? Do you need any package from PyPI, and how do you vet it? What would the legacy answer look like?

Rough sizing

Say 200 hostnames, a 5-second timeout each, and a run that must finish within 2 minutes.

Shape of the answer

ssl and socket from the standard library (ssl.create_default_context, getpeercert), found with pydoc -k ssl and help(ssl.SSLSocket.getpeercert); datetime with timezone-aware times; concurrent.futures for 20 at a time; urllib.request to post to the chat webhook, or requests if the team already uses it, pinned. Legacy to avoid: shelling out to openssl s_client and parsing its text.

Trade-offs to name

The standard library needs no install and no vetting, and takes a few more lines; a package can be shorter, and adds a dependency to pin, audit, and update.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
A copied legacy answerHop 6: Legacy or modern?BreaksThe forum answer: os.system("df -h " + path). It returns only the exit status, so the numbers cannot be read; the workaround, os.popen and string slicing, breaks on a mount with a space in its name and on a server set to another language.
A look-alike packageHop 7: Third-partyBreaksThe blog's install command names a package one letter off a popular one. Its install script reads environment variables and sends them to an outside server, including a CI token.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Describe the job → Ask the shell → Built in? → Look inside → How to call it → Legacy or modern? → Third-party → Try it small → Keep it. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 30
Python Lab: Clean the Data, Find the Slow Services

Lesson 28 taught you pandas and numpy. This lab is where you clean a real file. You get a five-row health check file with one blank latency, you fill the blank with the median, you flag the slow services, and you write the…

Go to Lesson 30 →

Or browse the full course from the Lessons index.