Sub topic 8
Feeding input to a command
This chapter assumes you can call subprocess.run, capture its output with capture_output=True, and know the difference between str and bytes. It covers the input argument, the stdin argument, and what happens when the child process does not read what you send.
What standard input is for
Many command-line programs read from standard input (stdin) instead of taking a file name. Examples are sort, grep, wc, and Python scripts that call sys.stdin.read(). In a terminal, stdin is your keyboard. When you start a child process from Python, you decide where its stdin comes from.
If you say nothing, the child inherits the parent's stdin. In a terminal, that means the child can wait for someone to type. In a service or a CI job, it can read nothing at all or hang. Most of this chapter is about not leaving that to chance.
Sending a string with input
The simplest way to feed a child is the input argument of subprocess.run. Python opens a pipe to the child's stdin, writes your data, closes the pipe, and then collects the output.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "import sys; print(sys.stdin.read().upper())"],
input="hello",
capture_output=True,
text=True,
)
print(result.stdout.strip())This prints HELLO. Closing the pipe matters. A program that calls sys.stdin.read() waits for end of file (EOF), which the child sees only when the write end of the pipe is closed. run does this for you once all the input is written.
Text mode and bytes mode
The type of input must match the mode of the call.
- With
text=True(orencoding=orerrors=),inputmust be astr. Python encodes it for you. - Without any of those,
inputmust bebytes, andresult.stdoutisbytestoo.
import subprocess
import sys
data = "café".encode("utf-8")
result = subprocess.run(
[sys.executable, "-c", "import sys; print(len(sys.stdin.buffer.read()))"],
input=data,
capture_output=True,
check=True,
)
print(result.stdout)The output is b'5\n'. The word "café" has four characters but five bytes in UTF-8, and the child counted bytes because it read from sys.stdin.buffer. Passing a str here, or bytes in text mode, fails with an exception. Match the types and the error does not occur.
In text mode, the encoding defaults to the locale's preferred encoding, which differs between machines. If the data is not plain ASCII, name the encoding on both sides:
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "import sys; print(sys.stdin.read().upper())"],
input="café",
encoding="utf-8",
capture_output=True,
check=True,
)
print(result.stdout.strip())The child's own stdin encoding is set by the child. A Python child uses its locale unless you set PYTHONIOENCODING or PYTHONUTF8 in its environment (see the chapter on environment variables).
Line endings and the final newline
Many tools expect input to be lines that each end in \n. input="pear\napple\nfig" has no final newline, and some programs treat the last line as incomplete. Build multi-line input deliberately:
import subprocess
import sys
lines = ["pear", "apple", "fig"]
payload = "\n".join(lines) + "\n"
result = subprocess.run(
[sys.executable, "-c", "import sys; print(''.join(sorted(sys.stdin)), end='')"],
input=payload,
capture_output=True,
text=True,
check=True,
)
print(result.stdout, end="")This prints apple, fig, and pear, one per line. In text mode, Python translates \n in your input to the platform's line ending (\r\n on Windows), and translates the child's line endings back to \n in the output.
Reading stdin from a file
If the data is already in a file, do not read it into memory. Give the child the open file as stdin, and the operating system connects them directly.
import subprocess
import sys
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "names.txt"
path.write_text("one\ntwo\nthree\n", encoding="utf-8")
with path.open("rb") as handle:
result = subprocess.run(
[sys.executable, "-c", "import sys; print(sum(1 for _ in sys.stdin))"],
stdin=handle,
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())This prints 3. The stdin argument accepts an open file object (anything with a real file descriptor), subprocess.PIPE, subprocess.DEVNULL, or None for "inherit". io.StringIO does not work, because it has no file descriptor. Use input= for in-memory data.
Giving the child no input
When a command should not read anything, use stdin=subprocess.DEVNULL. The child sees EOF immediately instead of waiting for a keyboard.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "import sys; print(repr(sys.stdin.read()))"],
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())This prints ''. It is a good default for tools that sometimes prompt, such as git, ssh, or pip. A prompt that nobody can answer would otherwise block your program. Combine it with a timeout (covered in the timeouts chapter) as a second safety net.
input and stdin together
input is shorthand for "open a pipe on stdin and write this". Because of that, run refuses to combine it with an explicit stdin:
import subprocess
import sys
try:
subprocess.run(
[sys.executable, "-c", "pass"],
input="x",
stdin=subprocess.DEVNULL,
)
except ValueError as exc:
print(exc)The message is stdin and input arguments may not both be used. Choose one source of input per call.
Edge cases
The child exits without reading
A child may exit before reading all your input, for example head -n 1 or a program that fails on startup. Writing to a closed pipe normally raises BrokenPipeError. The communicate method inside run catches that error and carries on, so you still get the output and return code. Check returncode (or use check=True) to learn whether the child succeeded.
Large input
You can send input much larger than the pipe buffer (commonly 64 KiB on Linux). run writes the input while it reads stdout and stderr, so the child cannot block on a full output pipe while you are still writing. This is the same mechanism that prevents the deadlocks described in the pipe deadlock chapter. If you use Popen and do the writing yourself, you take over that responsibility.
The whole input must fit in memory
input is one string or bytes object, and run collects all output before returning. For gigabytes of data, pass a file as stdin and write the output to a file with stdout=, or switch to Popen and stream.
Interactive programs
input is a single write followed by EOF. It cannot answer a prompt, wait for the reply, and then send more. Programs that ask for a password usually read from the terminal device directly (not stdin), so piping input does not work for them at all. Prefer a non-interactive option such as a flag, an environment variable, or a credentials file. For genuine back-and-forth conversations, use Popen and write to proc.stdin step by step, or a library built for terminals such as pexpect.
Summary of choices
| Goal | Use |
|---|---|
| Send a string or bytes you already have | `input=` with matching `text` mode |
| Send the contents of a file | `stdin=open_file` |
| Make sure the child never waits for input | `stdin=subprocess.DEVNULL` |
| Let the child use the terminal | Leave `stdin` unset (the default) |
| Hold a conversation with the child | `Popen` with `stdin=PIPE` |
Exercise
You run subprocess.run(["sort"], input=b"b\na\n", capture_output=True, text=True). It fails with an exception before you see any output. What is wrong, and give two ways to fix it?
Show answer
In text mode, input must be a str, but b"b\na\n" is bytes. Fix 1: pass a string, input="b\na\n". Fix 2: keep the bytes and remove text=True, so result.stdout is also bytes. Alternatively, keep text mode and decode the bytes first with .decode("utf-8").
Exercise
A script calls subprocess.run(["git", "pull"], capture_output=True, text=True) from a scheduled job. Sometimes the job hangs forever. Which argument most directly prevents the hang caused by a prompt, and what does the child see?
Show answer
Add stdin=subprocess.DEVNULL. The child then reads end of file immediately instead of waiting for input, so a prompt fails or is skipped instead of blocking. Adding a timeout as well limits the damage if the hang has some other cause.