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()?
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.
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 internalPopen
object is automatically created withstdin=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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With