How do I pass a string into subprocess.run using stdin?

Question:

This is certainly answered as part of a long discussion about subprocess elsewhere. But the answer is so simple it should be broken out.

How do I pass a string “foo” to a program expecting it on stdin if I use Python 3’s subprocess.run()?

Asked By: Ray Salemi

||

Answers:

Simplest possible example, send foo to cat and let it print to the screen.

 import subprocess

 subprocess.run(['cat'],input=b'foon')

Notice that you send binary data and the carriage return.

Answered By: Ray Salemi

Pass input="whatever string you want" and text=True to subprocess.run:

import subprocess
subprocess.run("cat", input="foon", text=True)

Per the docs for subprocess.run:

The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if encoding or errors is specified or text is true. When used, the internal Popen object is automatically created with stdin=PIPE, and the stdin argument may not be used as well.

To also get the output of the command as a string, add capture_output=True:

subprocess.run("cat", input="foon", capture_output=True, text=True)
Answered By: Boris Verkhovskiy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.