Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()?

like image 472
Ray Salemi Avatar asked Feb 12 '18 17:02

Ray Salemi


2 Answers

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.

like image 138
Ray Salemi Avatar answered Dec 04 '22 05:12

Ray Salemi


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")
like image 40
Boris Avatar answered Dec 04 '22 05:12

Boris