Popen communicate vs Popen stdin.write()

2019-09-08 12:54发布

问题:

I am using a java engine to process some content.

I am wondering will it take up unnecessary resources like this.

command = 'some command to run my jar file'
p = subprocess.Popen(command, stdout = subprocess.PIPE, stdin = subprocess.PIPE)

Comparing

output,err = p.communicate('some string that is passed to the java jar') 

vs

p.stdin.write('some string that is passed to the java jar \n')
p.stdin.flush() 
output = p.stdout.readline()

To give some context to the problem. The strings are generated on the fly and hence i do not want to open and close the java application everything a string is generated.

So for example:

My python engine creates a string

'Hi i am going home now' which is passed to the java engine to run and obtains the output.

Next it produces 'He is going home now' and the process repeats.

Obviously the java programs write to System.out.println(output);

回答1:

p.communicate() will wait for the process to terminate according to the subprocess docs. Unless you plan to terminate and restart your java process each time you communicate, the second method (read/write) is all you have available.