Sub topic 15
Differences between operating systems
This chapter assumes you know subprocess.run, argument lists, shell=True, check=True, timeouts, and the Popen basics from the earlier chapters. The examples from those chapters mostly use sys.executable, so they run unchanged on Windows, macOS and Linux. Real programs also call tools like git, ls or npm, and the three platforms start, find, and stop processes differently.
macOS and Linux are both POSIX systems and behave almost identically here. The real split is POSIX versus Windows.
How a command is started
On POSIX, Python forks and calls exec with your argument list as separate strings. The operating system never needs to join or split them.
Windows has no such call. Its CreateProcess function takes one command-line string, and the program parses its own arguments from it. When you pass a list, Python joins it into a string with Windows quoting rules. The child then splits it again.
The consequences:
- Quoting rules differ.
shlex.splitfollows POSIX shell rules. On Windows it can mangle backslashes in paths such asC:\Users\me. Prefer building lists directly instead of splitting strings. shell=Truemeans a different shell./bin/shandcmd.exeuse different quoting, different variable syntax ($HOMEversus%USERPROFILE%), and different escape characters. A string that works on one is rarely valid on the other.- Injection rules differ too. The list form avoids the shell on both platforms. On Windows, a target that is a
.bator.cmdfile is run throughcmd.exeanyway, so special characters in its arguments can still be interpreted. Treat batch files likeshell=Truefor untrusted input.
Finding the program
A table summarizes the main lookup differences.
| Topic | POSIX | Windows |
|---|---|---|
| Program names | Exact name, such as `git` | Extensions are tried, such as `git.exe`, depending on the search |
| Built-in commands | Few are shell-only; `echo` and `pwd` exist as programs | `dir`, `copy`, `type` and `echo` are `cmd.exe` built-ins, with no `.exe` |
| Executable bit | Required | Not used; the extension decides |
| Scripts | `#!` line selects the interpreter | `.py` files are not run directly by `CreateProcess` |
| Search path separator | `:` | `;` |
So subprocess.run(["dir"]) raises FileNotFoundError on Windows, because dir is not a program. Either use ["cmd", "/c", "dir"] or avoid the need, for example with os.listdir or pathlib. A Python script must be launched through the interpreter: [sys.executable, "script.py"], never ["script.py"].
The portable way to locate a tool is shutil.which. It honors PATH and, on Windows, the PATHEXT list of executable extensions. It returns None if nothing is found.
import shutil
import subprocess
import sys
def run_tool(name, *args, timeout=30):
exe = shutil.which(name)
if exe is None:
raise FileNotFoundError(f"{name} not found on PATH")
return subprocess.run(
[exe, *args],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
)
result = run_tool(sys.executable, "--version")
print(result.stdout.strip() or result.stderr.strip())shutil.which accepts a full path, so this works for sys.executable as well as for bare names. Resolving the path once also gives you a clear error message before launching. It avoids Windows searching a different place than you expected, such as the current directory.
Text, newlines and encodings
With text=True, Python decodes with the locale's preferred encoding by default. On Linux and macOS that is nearly always UTF-8. On Windows it is often a legacy code page such as cp1252, and console programs may write in yet another one (the OEM code page). The result is garbled accents, or UnicodeDecodeError, that never appears on your Linux machine.
Set the encoding explicitly, as run_tool does. Use errors="replace" when you only need to display or log the output. Remember that the child controls what it writes. Setting encoding="utf-8" only helps if the child really emits UTF-8, and Python children can be told to with PYTHONIOENCODING or -X utf8.
Text mode also uses universal newlines. \r\n from a Windows program becomes \n in result.stdout. In bytes mode, you see the raw \r\n, so strip or split carefully when comparing output across platforms.
Environment differences
Environment variable names are case-insensitive on Windows and case-sensitive on POSIX. env["Path"] and env["PATH"] are the same variable there but different ones on Linux.
A more common trap: building a minimal environment from scratch. A child Python process on Windows typically fails if SYSTEMROOT is missing. Copy the variables you need instead of passing only your own.
import os
import subprocess
import sys
keep = ["PATH", "SYSTEMROOT", "HOME", "USERPROFILE"]
env = {key: os.environ[key] for key in keep if key in os.environ}
env["GREETING"] = "hi"
result = subprocess.run(
[sys.executable, "-c", "import os; print(os.environ['GREETING'])"],
env=env,
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())Copying all of os.environ and adding to it, as shown earlier in the tutorial, is the simpler and safer default. Use a trimmed environment only when you have a reason, such as keeping secrets out of the child.
Use os.pathsep when you build a PATH-like value, and pathlib for file paths. Avoid hard-coded / or \ in anything you hand to a child.
Exit codes and signals
On POSIX, a process killed by a signal has a negative returncode. For example, -9 means SIGKILL and -15 means SIGTERM. Windows has no signals in this sense. A process exits with an unsigned 32-bit number, so a crash or Ctrl+C shows up as a large value such as 3221225786 (hex 0xC000013A). Do not write checks like returncode < 0 and expect them to work everywhere.
The methods terminate() and kill() also differ:
- On POSIX,
terminate()sends SIGTERM, which a program can catch and use to clean up.kill()sends SIGKILL, which cannot be caught. - On Windows, both call
TerminateProcess, which stops the process immediately with no cleanup. They are effectively the same. send_signal(signal.SIGINT)is not supported on Windows. OnlyCTRL_C_EVENTandCTRL_BREAK_EVENTare accepted, and they reach the child only if it was created withCREATE_NEW_PROCESS_GROUP.
Python flags that exist on one platform only:
creationflagsandstartupinfoapply to Windows. A non-zerocreationflagsraisesValueErroron POSIX.start_new_session,process_group,user,groupandumaskapply to POSIX.
Branch on sys.platform when you need either:
import subprocess
import sys
import time
if sys.platform == "win32":
extra = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
else:
extra = {"start_new_session": True}
proc = subprocess.Popen(
[sys.executable, "-c", "import time; time.sleep(30)"],
**extra,
)
time.sleep(0.5)
proc.terminate()
proc.wait()
print("return code", proc.returncode)On Linux and macOS this prints -15. On Windows it prints 1.
Timeouts and grandchildren
subprocess.run(..., timeout=...) kills only the process it started. With shell=True, that is the shell, and the real program it launched can keep running as an orphan. This is worse on Windows, where cmd.exe /c is a separate process. The fix is to avoid the shell, so the process you kill is the one doing the work. If the child itself spawns helpers, put it in its own session or process group, as above. Then you can signal the whole group on POSIX with os.killpg, or use taskkill /T /PID <pid> on Windows.
A practical checklist
- Launch Python tools with
sys.executable, neverpythonorpython3, which may not exist or may point at another interpreter. - Resolve other tools with
shutil.whichand handleNone. - Pass argument lists, and avoid
shell=Trueunless you need a shell feature and have written a command per platform. - Set
encodinganderrorsexplicitly when the text matters. - Isolate platform-only options behind a single
sys.platformcheck. - Test on every platform you claim to support, since a quoting bug or a missing built-in command will not show up elsewhere.
Exercise
A script runs subprocess.run(["ls", "-l"], capture_output=True, text=True, check=True) and works on Linux, but on Windows it raises FileNotFoundError. A second script calls subprocess.run(["dir"]) and fails the same way. Explain both failures and give a portable fix for each.
Show answer
On Windows, ls is not installed by default, so no such program is on PATH. dir is a cmd.exe built-in, not an executable file, so CreateProcess cannot find it either. For ls, avoid the external tool and use pathlib.Path(".").iterdir() or os.scandir, or resolve a real tool with shutil.which and raise a clear error if it returns None. For dir, use the same Python functions, or on Windows only call ["cmd", "/c", "dir"]. Python file APIs are the portable choice because they work the same on every platform.
Exercise
You start a child with subprocess.run(["sleep", "60"], timeout=5) on Linux and catch TimeoutExpired. What would you check on returncode if you used Popen and kill() instead, and why is that check not portable?
Show answer
After kill() and wait(), the return code is -9 on POSIX, because a negative value means the process was ended by that signal number. On Windows kill() calls TerminateProcess, so the code is a plain non-negative exit value (1), and a negative-number check never matches. A portable program should rely on its own timeout handling, such as the TimeoutExpired exception, rather than on specific return code values.