Sub topic 8
Feeding input to a command
This chapter assumes you can call subprocess.run, capture output with capture_output=True, and read CompletedProcess results. You also need to know what standard input (stdin) is: the stream a program reads data from when it is not given a file.
Why send input
Many command-line tools read from stdin. Examples are sort, grep, and python -c scripts that call sys.stdin.read(). Instead of writing a temporary file, you can hand the data to the child process directly.
The input argument
subprocess.run accepts an input argument. Python writes that value to the child's stdin, closes the stream, and then waits for the child to finish. Closing the stream matters because it tells the child there is no more data, so programs that read until end of input can stop.
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. The child reads hello, converts it to uppercase, and prints it. The parent captures that output.
Text or bytes
The type of input must match the mode of the call.
| Mode | Set by | `input` type |
|---|---|---|
| Text | `text=True` (or `encoding=`) | `str` |
| Bytes | default | `bytes` |
With text=True, Python encodes your string before sending it and decodes the output it captures. Without it, pass bytes such as b"hello" and expect bytes back.
What happens inside run
When you pass input, run sets up a pipe for stdin and uses communicate() internally. communicate() writes the data, reads the output, and waits for exit. This avoids a common deadlock, where the parent blocks writing to a full pipe while the child blocks writing its own output. A later chapter covers that problem in detail.
Common errors
- Missing newline. Some programs process input line by line and ignore a final line with no newline. If the child seems to drop your last line, end the input with
"\n". - Using
inputandstdintogether.runraisesValueErrorif you pass bothinputandstdin=. Pick one. - Expecting interaction.
inputis sent once. If the child asks a question, waits for your answer, and then asks another,runcannot respond to each prompt. That job needsPopen, covered later. - Forgetting to capture output. Without
capture_output=True, the child's output goes to your terminal andresult.stdoutisNone.
Sending a file as input
To feed a whole file, pass an open file object as stdin instead of reading it into memory. This suits large files.
import subprocess
import sys
import tempfile
with tempfile.TemporaryFile("w+") as f:
f.write("one two three")
f.seek(0)
result = subprocess.run(
[sys.executable, "-c", "import sys; print(len(sys.stdin.read().split()))"],
stdin=f,
capture_output=True,
text=True,
)
print(result.stdout.strip())This prints 3. The seek(0) call is needed because writing leaves the file position at the end, and the child would read nothing.
Exercise
A script calls subprocess.run(["sort"], input="b\na\n", capture_output=True) and raises a TypeError. What is wrong, and how do you fix it?
Show answer
The call passes a str as input but does not enable text mode, so run expects bytes. Add text=True, or pass b"b\na\n" and decode result.stdout yourself.