Python Standard Library · Lesson 122 of 149

Python os, sys and shutil

What you will learn

  • os: environment variables, the working folder, files and os.path
  • sys: arguments, platform, exit codes, the interpreter
  • shutil: copying, moving, archives, disk space
  • subprocess: running other programs
  • How these relate to pathlib

1. Programs and their environment

A program does not live alone: it runs on an operating system, has settings passed in, uses folders, and sometimes starts other programs. Four modules cover this:

Module Talks to
os the operating system: environment, folders, processes
sys the Python interpreter: arguments, platform, exit
shutil file-level jobs: copy, move, archive, disk usage
subprocess other programs

For paths and file contents, prefer pathlib (lesson 15.4); os is still common in older code and for the jobs below.

2. os: environment variables

Environment variables are named text settings given to a program by its surroundings (a path, a user name, a secret key). os.environ acts like a dictionary:

import os

print(os.environ.get("NOPE_XYZ"))
print(os.environ.get("NOPE_XYZ", "default"))

os.environ["MY_VAR"] = "hello"
print(os.environ["MY_VAR"], os.getenv("MY_VAR"), os.getenv("MISSING", "none"))
os.environ["NOPE_XYZ2"]
None
default
hello hello none
KeyError: 'NOPE_XYZ2'
  • os.environ.get(name, default) and os.getenv(name, default) are the safe way to read: they return the default instead of raising KeyError.
  • Values are always strings: convert with int(...) when needed.
  • Changing os.environ affects the current program and the programs it starts, not the terminal that launched it.

Environment variables are the usual home for settings that differ between machines and for secrets such as passwords and API keys, which must never be written into source code or committed to git. A program reads os.environ.get("DATABASE_URL"), and the real value is set on the server.

Quick check: why prefer `os.environ.get("X")` to `os.environ["X"]`?

get returns None (or your default) if the variable is missing; the bracket form raises KeyError.

3. os: working with the system

print(os.name, os.sep, os.pathsep)
print(os.getcwd() == str(Path.cwd()))
nt \ ;
True

(From a Windows computer: os.name is nt, folders are separated by \, and entries in PATH by ;. On Linux and macOS you would see posix, / and :.) os.getcwd() is the current working folder; os.chdir(folder) changes it. Files and folders:

import os
from pathlib import Path

os.makedirs("a/b/c", exist_ok=True)
print(os.path.isdir("a/b/c"), os.listdir("a"))

Path("a/f.txt").write_text("hello")
print(os.path.getsize("a/f.txt"), os.path.exists("a/f.txt"), os.path.isfile("a/f.txt"))

os.rename("a/f.txt", "a/g.txt")
print(sorted(os.listdir("a")))

os.remove("a/g.txt")
os.rmdir("a/b/c")
print(sorted(os.listdir("a")))
True ['b']
5 True True
['b', 'g.txt']
['b']
os function pathlib equivalent
os.makedirs(p, exist_ok=True) Path(p).mkdir(parents=True, exist_ok=True)
os.listdir(p) Path(p).iterdir()
os.rename(a, b) Path(a).rename(b)
os.remove(p) Path(p).unlink()
os.rmdir(p) Path(p).rmdir()
os.path.exists(p) Path(p).exists()

String helpers in os.path:

print(os.path.splitext("report.final.pdf"))
print(os.path.basename("a/b/c.txt"), os.path.dirname("a/b/c.txt"), os.path.split("a/b/c.txt"))
print(os.path.join("a", "b", "c.txt").replace("\\", "/"))
('report.final', '.pdf')
c.txt a/b ('a/b', 'c.txt')
a/b/c.txt

Also: os.cpu_count() (number of processors, lesson 20.1) and os.getpid() (this program's process number).

4. sys: the interpreter

sys describes the running Python:

Name Meaning
sys.argv the command-line arguments, as a list of strings
sys.platform "win32", "linux", "darwin" (macOS)
sys.version_info the Python version as a tuple
sys.executable the path of the running Python (lesson 16.4)
sys.path the module search path (lesson 16.4)
sys.stdin, stdout, stderr the standard streams (lesson 15.3)
sys.exit(code) stop the program
sys.maxsize the largest size of a container: 9223372036854775807 on a 64-bit Python
import sys

print(sys.platform)
print(sys.version_info[:2] >= (3, 8))
print(len(sys.argv), sys.argv[0].endswith(".py"))
win32
True
1 True

Command-line arguments

sys.argv[0] is the script name and the rest are the arguments typed after it. Running python backup.py one two gives sys.argv equal to ['backup.py', 'one', 'two'], so len(sys.argv) - 1 is the number of arguments given. For anything beyond one or two simple arguments, use argparse (lesson 17.8), which handles options, help messages and errors.

Exit codes

A program ends with an exit code: 0 means success, anything else means failure. Other programs (and scripts) check it. sys.exit(3) stops the program with code 3; sys.exit("message") prints the message to standard error and exits with code 1. Run in child processes (section 6) with subprocess.run, sys.exit(3) gave returncode 3, and sys.exit('bad') gave returncode 1 with the text bad in stderr.

sys.exit works by raising SystemExit, which is why except Exception does not catch it (lesson 14.2).

5. shutil: files at a higher level

shutil (lesson 15.5) copies, moves and deletes whole trees. It also makes archives and reports disk space:

import shutil
from pathlib import Path

print(shutil.which("python") is not None)
print(shutil.disk_usage(".").total > 0)
print(shutil.get_terminal_size().columns > 0)

shutil.copy2("backup.py", "copy.py")
shutil.make_archive("bundle", "zip", root_dir=".", base_dir="copy.py")
print(Path("bundle.zip").exists())
shutil.unpack_archive("bundle.zip", "out")
print(sorted(p.name for p in Path("out").iterdir()))
True
True
True
True
['copy.py']
  • shutil.which(name) finds a program on the system PATH (or None).
  • shutil.disk_usage(folder) returns total, used and free bytes.
  • shutil.make_archive(base_name, format, root_dir) creates a zip or tar archive of a folder; unpack_archive extracts it. The zipfile module reads and writes zip files directly (ZipFile(path).namelist() lists the contents).
  • Only unpack archives from sources you trust: a hostile archive can try to write files outside the target folder.

6. subprocess: running other programs

subprocess.run starts another program, waits for it, and reports the result:

import subprocess
import sys

result = subprocess.run([sys.executable, "-c", "print(2 + 3)"],
                        capture_output=True, text=True)
print(result.stdout.strip(), result.returncode)
5 0
  • The command is a list of words: the program, then its arguments. sys.executable is the same Python that is running now.
  • capture_output=True collects what the program prints into result.stdout and result.stderr; text=True gives strings instead of bytes.
  • result.returncode is the exit code (0 = success).
  • check=True raises subprocess.CalledProcessError if the exit code is not zero:
try:
    subprocess.run([sys.executable, "-c", "import sys; sys.exit(2)"], check=True)
except subprocess.CalledProcessError as e:
    print("CalledProcessError:", e.returncode)
CalledProcessError: 2

Environment variables set in os.environ are inherited by the child: in the check, a child Python program printed hello for MY_VAR.

Safety: pass a list, not a single text string, and avoid shell=True, especially with text that came from a user. A user-supplied value like x; delete everything inside a shell string could run extra commands (an "injection" attack). With a list, each item is a plain argument, never a command.

Worked example: a small backup script

backup.py reads the destination from an environment variable (with a default), zips a data folder with shutil, lists the archive, runs a child program with subprocess, and reports how many command-line arguments it was given. It was run from a clean folder.

import os
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path


def disk_report(folder="."):
    usage = shutil.disk_usage(folder)
    return f"{usage.used / usage.total:.0%} used"


def backup(source, target_dir, name="backup"):
    source = Path(source)
    target_dir = Path(target_dir)
    target_dir.mkdir(parents=True, exist_ok=True)
    archive = shutil.make_archive(str(target_dir / name), "zip", root_dir=source)
    return Path(archive)


src = Path("data")
src.mkdir(exist_ok=True)
(src / "a.txt").write_text("alpha")
(src / "b.txt").write_text("beta")

dest = os.environ.get("BACKUP_DIR", "backups")
print("destination:", dest)
zip_path = backup(src, dest)
print(zip_path.name, zip_path.exists())
with zipfile.ZipFile(zip_path) as z:
    print(sorted(z.namelist()))

result = subprocess.run([sys.executable, "-c", "print(2 + 3)"],
                        capture_output=True, text=True)
print("child says:", result.stdout.strip(), "| exit code", result.returncode)

print(sys.platform in ("win32", "linux", "darwin"), disk_report().endswith("% used"))
print(len(sys.argv) - 1, "arguments given")

Running python backup.py:

destination: backups
backup.zip True
['a.txt', 'b.txt']
child says: 5 | exit code 0
True True
0 arguments given

and BACKUP_DIR=other python backup.py one two (the Linux and macOS way to set a variable for one run) printed:

destination: other
backup.zip True
...
2 arguments given
Part Idea
os.environ.get("BACKUP_DIR", "backups") a setting from outside, with a default
shutil.make_archive one call zips a whole folder
zipfile.ZipFile confirms what is inside the archive
subprocess.run([...], capture_output=True, text=True) runs a program and captures its output
sys.argv counts arguments typed after the script name

The file contents are made up. The percentage from disk_report is not printed because it depends on the computer.

Common mistakes

  • Writing secrets into code instead of reading environment variables.
  • Using os.environ["X"] when the variable might be missing.
  • Forgetting that environment values are strings.
  • shell=True with user input in subprocess.
  • Not checking the exit code of a program you started.
  • Joining paths with + instead of os.path.join or pathlib.
  • Changing the working folder with os.chdir and getting lost; use full paths.
  • Unpacking untrusted archives.

Key takeaways

  • os.environ / os.getenv read settings and secrets from the environment; values are strings, and .get avoids KeyError.
  • os offers folder and file functions, most of which pathlib does more cleanly.
  • sys.argv holds the command-line arguments; sys.exit(code) ends the program (0 means success); sys.platform and sys.version_info describe the system.
  • shutil copies, moves and archives; subprocess.run([...], capture_output=True, text=True) runs other programs safely.
  • Avoid shell=True with untrusted text.

Practice

1. How do you read the variable API_KEY, falling back to "none"?

Show answer

os.environ.get("API_KEY", "none") (or os.getenv("API_KEY", "none")).

2. What does python tool.py a b c put in sys.argv?

Show answer

['tool.py', 'a', 'b', 'c'].

3. What exit code means success?

Show answer

0. Any other value signals a failure.

4. Why pass a list to subprocess.run rather than one string?

Show answer

Each list item is a plain argument, so special characters in user text cannot be run as extra shell commands.

5. Which module creates a zip of a folder in one call?

Show answer

shutil.make_archive(name, "zip", root_dir=folder).

6. Why should a database password not be in the source code?

Show answer

Anyone who can read or copy the code (or its git history) would get the password. Read it from an environment variable set on the server.