无法从 python 脚本与 java 程序进行通信。 我有一个从标准输入读取的java程序。 逻辑是:
public static void main(String[] args) {
...
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String cmd;
boolean salir = faslse
while (!salir) {
cmd = in.readLine();
JOptionPane.showMessageDialog(null, "run: " + cmd);
//execute cmd
...
System.out.println(result);
System.out.flush();
}
}
我通过console控制台运行程序
java -cp MyProgram.jar package.MyMainClass
并执行命令并获取结果,并在对话框中显示执行的命令(JOptionPane.showMessageDialog(null, "run: "+ cmd); )
我需要从 python 调用该程序。 现在我正在尝试这样做:
#!/usr/bin/python
import subprocess
p = subprocess.Popen("java -cp MyProgram.jar package.MyMainClass", shell=True, stdout=subprocess.PIPE , stdin=subprocess.PIPE)
print '1- create ok'
p.stdin.write('comand parameter1 parameter2')
print '2- writeComand ok'
p.stdin.flush()
print '3- flush ok'
result = p.stdout.readline() # this line spoils the script
print '4- readline ok'
print result
p.stdin.close()
p.stdout.close()
print 'end'
输出是
1- create ok
2- writeComand ok
3- flush ok
并且不显示对话框。
但是如果我运行:
#!/usr/bin/python
import subprocess
p = subprocess.Popen("java -cp MyProgram.jar package.MyMainClass", shell=True, stdout=subprocess.PIPE , stdin=subprocess.PIPE)
print '1- create ok'
p.stdin.write('comand parameter1 parameter2')
print '2- writeComand ok'
p.stdin.flush()
print '3- flush ok'
p.stdin.close()
p.stdout.close()
print 'end'
输出为
1- create ok
2- writeComand ok
3- flush ok
end
并显示显示对话框。
p.stdout.readline() 行破坏了脚本,我可以修复这个问题吗?
非常感谢您的帮助。
最佳答案
仅打印一个结果
后刷新您的System.out
。
另外更改您的代码来执行此操作:
p = subprocess.Popen("java -cp MyProgram.jar package.MyMainClass",
shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
p.stdin.write(command1)
p.stdin.flush() # this should trigger the processing in the Java process
result = p.stdout.readline() # this only proceeds if the Java process flushes
p.stdin.write(command2)
p.stdin.flush()
result = p.stdout.readline()
# and afterwards:
p.stdin.close()
p.stdout.close()
关于java - 从 python 脚本执行另一个程序的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16451837/