How do I pass a string in to subprocess.run using stdin in Python 3

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

import subprocess
subprocess.run("cat", text=True, input="foo\n")

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.


universal_newlines was renamed to text in Python 3.7, so on older versions you have to use universal_newlines=True instead of text=True:

subprocess.run("cat", universal_newlines=True, input="foo\n")

and you might want to add capture_output=True if you want the output of the command as a string:

subprocess.run("cat", universal_newlines=True, capture_output=True, input="foo\n")

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

 import subprocess

 subprocess.run(['cat'],input=b'foo\n')

Notice that you send binary data and the carriage return.