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
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.
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.
Pick a job and where you take the answer from. See what you end up using.
Legacy: parsing df text breaks on long names and other languages
Three questions. No score is saved anywhere — this is just you against the material.
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.
At the basic level you know where help lives.
man -k, whatis, --help, man, type, help.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.
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.python3 -W default shows deprecation warnings.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.
At the advanced level you vet what you install.
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.
At the master level the search is shared, not repeated.
os.system, shell=True, yaml.load).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.
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 way | Current way | Why |
|---|---|---|
os.system, os.popen, commands | subprocess.run([...], capture_output=True, text=True) | output, errors, and exit code; no shell |
os.path.join, glob.glob | pathlib.Path | paths as objects |
optparse, getopt | argparse | help, types, and sub-commands built in |
urllib2 (Python 2) | urllib.request, or requests | renamed in Python 3 |
"%s" % x, "{}".format(x) | f-strings | shorter, clearer |
datetime.utcnow() | datetime.now(datetime.UTC) | deprecated; the new one knows its timezone |
time.time() for durations | time.monotonic() | never jumps when the clock is set |
imp, distutils | importlib, setuptools | removed in Python 3.12 |
yaml.load(f) | yaml.safe_load(f) | the old one can run code from the file |
logging.warn | logging.warning | deprecated spelling |
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.
pip install line into the CI requirements. The name is one letter off a popular package.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.
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.
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']
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
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']
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.
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')
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'
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
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
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
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
Write each one from scratch before you open the solution. The output under each solution is what it really prints.
Print the names in the string module that start with ascii, and the value of string.digits.
# 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
Print the signature of json.dump and the first line of its documentation.
# 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)
Decide whether tomllib, toml, and zoneinfo are built in; for the ones that are, print the first few public names they offer.
# 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']
Catch the warning from datetime.datetime.utcfromtimestamp(0) and print its category and the replacement it suggests.
# 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).
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.
Type each one, read what it prints, and compare it with the note above it.
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
Describe the job, then search the manuals by meaning and read one-line summaries.
man -k "space usage" | head -n 5 whatis df du
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
Read how to call the function you found, without leaving the terminal.
python3 -m pydoc shutil.disk_usage | head -n 12
Try it small, then compare it with df.
python3 -c "import shutil; print(shutil.disk_usage('/'))"
df -B1 / | tail -n 1See the deprecation warnings Python hides by default; each one names the new way.
python3 -W default -c "import datetime; datetime.datetime.utcnow()"
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)"
explain.pyThis 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
shutil.disk_usage is built in and does the whole job; no command, no parsing.os.system and utcnow still exist, and the program names their replacements; yaml and requests are not built in, so they need an install (as pyyaml and requests).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
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
grep, head, tail, df, du, mkdir, echo, cd, Pipes, Redirection, If...Else.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.
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?
Say 200 hostnames, a 5-second timeout each, and a run that must finish within 2 minutes.
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.
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.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| A copied legacy answer | Hop 6: Legacy or modern? | Breaks | The 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 package | Hop 7: Third-party | Breaks | The 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. |
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.