Sub topic 3
Passing arguments: lists, strings and shell=True
This chapter assumes you can call subprocess.run and read a CompletedProcess. The first argument to run is the command. You can pass it as a list or as a string, and the two forms behave differently.
The list form
A list holds the program name first and then one element per argument. Python hands each element to the program unchanged. No shell is involved, so spaces and punctuation have no special meaning.
import subprocess
import sys
subprocess.run(
[sys.executable, "-c", "import sys; print(sys.argv[1:])", "my file.txt", "a;b"]
)This prints ['my file.txt', 'a;b']. The space and the semicolon arrive as ordinary characters. Use the list form by default.
The string form
On Linux and macOS, a plain string without shell=True is treated as the name of one program. The whole string, spaces included, is looked up as an executable name:
import subprocess
try:
subprocess.run("echo hi")
except FileNotFoundError as exc:
print("not found:", exc.filename)This prints not found: echo hi. On Windows a string is accepted and passed to the operating system as a single command line, which the new program then splits itself. Code that relies on this is not portable.
What shell=True changes
With shell=True, the string goes to a shell: /bin/sh on POSIX systems, cmd.exe on Windows. The shell parses it. This gives you pipes, * globbing, $VARIABLE expansion and shell built-ins.
import subprocess
subprocess.run("echo hello | tr a-z A-Z", shell=True)The cost is that you must now quote every inserted value correctly. If you don't, the shell can read parts of your data as commands.
Using shlex
shlex.split turns a trusted command string into a list by applying shell-style quoting rules. shlex.quote escapes one value so that a POSIX shell reads it as a single word.
import shlex
import subprocess
print(shlex.split("ls -l 'my folder'"))
name = "my file.txt"
subprocess.run(f"echo {shlex.quote(name)} | wc -c", shell=True)The first line prints ['ls', '-l', 'my folder']. The run call prints 12, the length of the name plus a newline. Apply shlex.split to strings you wrote yourself. It does not make untrusted input safe, because the program you launch may still interpret the arguments in surprising ways. Windows cmd.exe follows different quoting rules, and shlex.quote does not apply there.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `FileNotFoundError` for a string like `"ls -l"` | The string was read as one program name | Pass a list, or use `shlex.split` |
| `["ls -l"]` fails | A single list element holding two words | Split it into `["ls", "-l"]` |
| `["ls", "*.py"]` lists nothing | No shell, so no globbing | Use `glob.glob` in Python |
| `["echo", "$HOME"]` prints `$HOME` | No shell, so no expansion | Use `os.environ["HOME"]` |
| List with `shell=True` ignores arguments on POSIX | Only the first element is the command | Pass one string, or drop `shell=True` |
Exercise
Why does subprocess.run("ls -l") raise FileNotFoundError on Linux, and what are two ways to fix it?
Show answer
Without shell=True, a string is read as the name of a single program, so Python looks for an executable literally called "ls -l". Fix it by passing a list, ["ls", "-l"], or by using shlex.split("ls -l") to produce that list. Adding shell=True also works, but it is the less safe choice.