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()?
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.
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)
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'foon')
Notice that you send binary data and the carriage return.
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 internalPopen
object is automatically created withstdin=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)