Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicating multiple times with a subprocess [duplicate]

I'm trying to pipe input to a program opened as a subprocess in Python. Using communicate() does what I want, but it only does so once, then waits for the subprocess to terminate before allowing things to continue.

Is there a method or module similar to communicate() in function, but allows multiple communications with the child process?

Here's an example:

import subprocess

p = subprocess.Popen('java minecraft_server.jar',
                 shell=True,
                 stdin=subprocess.PIPE);

//Pipe message to subprocess console here

//Do other things

//Pipe another message to subprocess console here

If this can be done in an easier fashion without using subprocess, that would be great as well.

like image 945
Sean Avatar asked Aug 10 '10 20:08

Sean


1 Answers

You can write to p.stdin (and flush every time to make sure the data is actually sent) as many separate times as you want. The problem would be only if you wanted to be sure to get results back (since it's so hard to convince other processes to not buffer their output!-), but since you're not even setting stdout= in your Popen class that's clearly not a problem for you. (When it is a problem, and you really need to defeat the other process's output buffering strategy, pexpect -- or wexpect on Windows -- are the best solution -- I recommend them very, very often on stackoverflow, but don't have the URLs at hand right now, so pls just search for them yourself if, contrary to your example, you do have that need).

like image 191
Alex Martelli Avatar answered Sep 30 '22 07:09

Alex Martelli