[英]execute commands from another program from a python script
无法通过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();
}
}
我通过控制台控制台运行程序
java -cp MyProgram.jar包.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()行破坏了脚本,因为我可以解决此问题?
非常感谢您的帮助。
仅打印一个result
后,刷新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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.