Sub topic 15
Differences between operating systems
This chapter assumes you can use subprocess.run, pass argument lists, and capture output as text. It covers where the same code behaves differently on Windows, macOS and Linux. macOS and Linux are both POSIX systems, so they behave alike. Windows is the outlier.
Shell built-ins are not programs
On Linux and macOS, ls, cat and echo are separate executable files. On Windows, dir, echo and copy are built into cmd.exe, so no dir.exe exists. This call works on POSIX and raises FileNotFoundError on Windows:
import subprocess
subprocess.run(["echo", "hi"])Prefer a cross-platform program. When you cannot, branch on sys.platform, as the example in the next section does.
How the program is found
POSIX looks for the name in each PATH directory and requires the execute permission bit. Windows also tries the extensions listed in PATHEXT, such as .exe and .bat, but CreateProcess only adds .exe for you. Running a .bat or .cmd script without shell=True can fail, so name the file with its extension.
shutil.which applies the platform's lookup rules and returns the full path, or None. Use it to check that a tool exists before you run it.
import shutil
import subprocess
import sys
git = shutil.which("git")
if git is None:
raise SystemExit("git is not installed or not on PATH")
result = subprocess.run(
[git, "--version"],
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())
if sys.platform == "win32":
listing = ["cmd", "/c", "dir", "/b"]
else:
listing = ["ls"]
print(subprocess.run(listing, capture_output=True, text=True).returncode)Quoting and `shlex`
On POSIX, a list becomes an argument vector that is passed straight to the new process. On Windows, the process receives one command-line string, and Python builds it from your list with subprocess.list2cmdline. The child program then splits that string using its own rules.
shlex.split follows POSIX shell rules by default. On Windows paths, the backslash is treated as an escape character and gets removed:
import shlex
print(shlex.split(r"C:\tools\app.exe --x"))Do not use it to parse Windows command lines. Build the list yourself instead.
Other differences
| Area | POSIX (Linux, macOS) | Windows |
|---|---|---|
| Built-in commands | Mostly real programs | `dir`, `echo` and others need `cmd /c` |
| Script files | Need a shebang line and execute permission | `.bat` and `.cmd` need a shell or an explicit `cmd /c` |
| Default text encoding | Usually UTF-8 | Often a legacy code page |
| Process options | `start_new_session`, `preexec_fn` | `creationflags` |
| Timeout kill | Sends `SIGKILL` | Calls `TerminateProcess` |
Two more points apply to every platform:
- Use
sys.executableto start another Python, as the earlier examples do. A barepythonmay be missing, may point to Python 2, or may belong to a different virtual environment. - With
text=True, line endings are normalized to\n, so Windows\r\ndoes not reach your code. In bytes mode you see the raw\r\n.
Killing a timed-out child does not kill the processes it started. Process groups and job objects are platform-specific, so grandchildren may keep running after TimeoutExpired.
Exercise
A script runs subprocess.run(["dir"], check=True). It works for you on Windows only when you add shell=True, and it fails on Linux either way. Why, and what is a portable fix?
Show answer
On Windows, dir is a cmd.exe built-in, so it only works through a shell. On Linux there is no dir shell command to run unless the coreutils dir program happens to be installed, so the call fails or behaves differently. A portable fix is to avoid the command and use Python, for example os.listdir() or pathlib.Path.iterdir(). If you must call an external tool, choose it by sys.platform and check it with shutil.which.