Sub topic 3
Passing arguments: lists, strings and shell=True
This chapter assumes you can call subprocess.run, read a CompletedProcess, and handle exceptions in Python. It also assumes you know that a command line is a program name followed by arguments. Here you will learn how subprocess turns your Python values into a command, and what changes when you add shell=True.
The first argument has two forms
subprocess.run accepts the command as a list of strings or as one string. The list form is the default choice. Each item is one argument, and Python hands the items to the operating system without any parsing.
import subprocess
import sys
subprocess.run(
[sys.executable, "-c", "import sys; print(sys.argv[1:])", "my file.txt", "-v"]
)This prints ['my file.txt', '-v']. The space in my file.txt causes no trouble, because the list already says where each argument starts and ends. You never need to add quotes or escape characters in the list form.
- The first item is the program to run.
- Every later item arrives in the child's
sys.argv(orargvin C) as exactly one argument. - Items must be strings or path-like objects. Convert numbers with
str(8080)first.
What happens with a string and no shell
On Linux and macOS, a string without shell=True is treated as the name of the program, not as a command line. A string containing spaces is therefore looked up as one long file name.
import subprocess
try:
subprocess.run("ls -l")
except FileNotFoundError as exc:
print("could not start:", exc)On Linux and macOS this prints a FileNotFoundError, because no program is named ls -l. The error is not about the file you wanted to list. It means the whole string was used as the program name.
On Windows the same call may work. Windows programs receive one command-line string, so subprocess passes your string through to the system. This difference is one reason to prefer lists everywhere. The portability chapter returns to it.
Splitting a string with shlex
Sometimes you have a command as a string, for example from a config file you control. shlex.split breaks it into a list using shell-like quoting rules.
import shlex
print(shlex.split("ls -l 'my folder'"))
print(shlex.split('git commit -m "fix: handle empty input"'))
print(shlex.join(["ls", "my folder"]))
print(shlex.quote("report.txt; echo injected"))The output is:
['ls', '-l', 'my folder']
['git', 'commit', '-m', 'fix: handle empty input']
ls 'my folder'
'report.txt; echo injected'shlex.splitturns a string into a list. Quotes group words, and the quote characters are removed.shlex.joinis the reverse. It builds a string in which each item is quoted when needed.shlex.quotequotes a single value so a POSIX shell reads it as one word.
shlex follows POSIX shell rules by default. Do not use it to split Windows command lines, where backslashes in paths are ordinary characters. shlex.split(r"C:\tools\app.exe") would treat the backslashes as escapes and damage the path.
A good pattern is to split once, then build the list yourself.
import shlex
import subprocess
import sys
base = shlex.split("-c 'import sys; print(sys.argv[1:])'")
subprocess.run([sys.executable, *base, "extra argument"])The trusted, fixed part comes from shlex.split. The variable part is appended as a single list item and is never re-parsed.
What shell=True changes
With shell=True, subprocess does not start your program directly. It starts a shell (/bin/sh on POSIX, cmd.exe on Windows) and gives it your string to interpret. The shell then does the parsing and starts the real program.
import subprocess
subprocess.run("echo one two three | wc -w", shell=True)On Linux and macOS this prints 3. The | is shell syntax, not an argument to echo. The shell sets up the pipe and starts both programs.
The shell gives you features that a plain list does not:
| Feature | Example | With a list and no shell |
|---|---|---|
| Pipes and redirection | `sort < in.txt > out.txt` | Not available. Use `stdin=`, `stdout=` or `Popen`. |
| Wildcard expansion | `ls *.py` | The `*` stays a literal character. |
| Variable expansion | `echo $HOME` | Not expanded. Use `os.environ`. |
| Chaining | `make && make install` | Not available. Run two commands and check each. |
| Built-in commands | `cd`, `export` (POSIX) | Not programs, so they cannot be started this way. |
The cost is that every character in the string is now shell syntax. If any part of the string comes from outside your program, an attacker can add commands to it. The next chapters cover injection in detail. For now, follow this rule: never build a shell=True string with f-strings from user data.
Wildcards do not expand without a shell
A common surprise is passing *.py in a list and expecting a file list. No shell is present, so the child receives the literal text.
import glob
import subprocess
import sys
show = [sys.executable, "-c", "import sys; print(sys.argv[1:])"]
subprocess.run([*show, "*.py"])
subprocess.run([*show, *sorted(glob.glob("*.py"))])The first call prints ['*.py']. The second prints whatever Python files are in the current directory. Using glob.glob in Python is the portable replacement for shell wildcards, and it keeps your arguments as separate items.
The list with shell=True trap
Combining a list with shell=True does not do what it appears to do. On POSIX, only the first item is the command string. The remaining items become arguments to the shell itself, not to your command.
import subprocess
subprocess.run(["echo", "hello"], shell=True)On Linux and macOS this prints an empty line. The shell runs echo with no arguments, and "hello" becomes the shell's $0. Choose one form: a list with shell=False, or a single string with shell=True.
How to choose
In practice:
- Start with a list and
shell=False. - If a wildcard or pipe tempts you, look for the Python equivalent first:
glob,pathlib,os.environ, or a secondPopencall. - Use
shell=Trueonly for a fixed string you wrote yourself. If you must include a variable value, wrap it withshlex.quote, and accept that this is only safe for POSIX shells.
Common errors
FileNotFoundErrorfor a string with spaces. You passed a command line withoutshell=True. Use a list orshlex.split.- A program receives one argument containing spaces, like
"-l -a". You put two arguments in one list item. Write["ls", "-l", "-a"]. - A program receives quote characters as part of its values. You added quotes inside a list item, such as
'"my file"'. In list form, write"my file"without extra quotes. - Wildcards or
$HOMEappear literally. No shell ran. Usegloboros.path.expanduser. - Output is empty when the list is combined with
shell=True. See the trap above.
Exercise
A teammate writes subprocess.run(["grep", "-r", "TODO", "src/*.py"]) and it finds nothing, although grep -r TODO src/*.py works in the terminal. Why, and how would you fix it without shell=True?
Show answer
In the terminal, the shell expands src/*.py into a list of file names before grep starts. With a list and no shell, grep receives the literal text src/*.py, which is not a file. Expand the pattern in Python instead: subprocess.run(["grep", "-r", "TODO", *sorted(glob.glob("src/*.py"))]), after import glob. This keeps each file name as its own argument.