Popen 通信 vs Popen stdin.write()

Popen communicate vs Popen stdin.write()

我正在使用 java 引擎来处理一些内容。

我想知道这样会不会占用不必要的资源。

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

比较

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

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

为问题提供一些背景信息。字符串是即时生成的,因此我不想打开和关闭 java 应用程序生成的所有字符串。

例如:

我的 python 引擎创建了一个字符串

'Hi i am going home now'传递给java引擎到运行并获得输出。

接下来它生成“He is going home now”并重复该过程。

显然 java 程序写入 System.out.println(output);

p.communicate()会根据the subprocess docs等待进程终止。除非您打算在每次通信时终止并重新启动您的 java 进程,否则第二种方法 (read/write) 是您唯一可用的方法。