KFL
KFL

Reputation: 17870

In Python how to pipe a string into an executables stdin?

On Windows I have a program (prog.exe) that reads from stdin. In python I want to pipe a string as the input to its stdin. How to do that?

Something like:

subprocess.check_output("echo {0} | myprog.exe".format(mystring)) 

or (to make the args a list)

subprocess.check_output("echo {0} | myprog.exe".format(mystring).split())

doesn't seem to work. It gave me:

WindowsError: [Error 2] The system cannot find the file specified

I also tried to use the "stdin" keyword arg with StringIO (which is a file-like object)

subprocess.check_output(["myprog.exe"], stdin=StringIO(mystring))

Still no luck - check_output doesn't work with StringIO.

Upvotes: 2

Views: 1267

Answers (1)

wim
wim

Reputation: 363364

You should use Popen communicate method (docs).

proc = subprocess.Popen(["myprog.exe"], stdin=subprocess.PIPE)
stdout, stderr = proc.communicate('my input')

Upvotes: 7

Related Questions