从python脚本执行另一个程序的命令
问题描述:
无法使用java程序与python脚本进行通信。 我有一个Java程序,从标准输入读取。 逻辑是:从python脚本执行另一个程序的命令
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命令MyProgram.jar package.MyMainClass
和执行命令和得到的结果,并显示命令在对话框中执行(JOptionPane.showMessageDialog(null,“run:”+ cmd);)
我需要调用程序蟒蛇。 现在,我想这一点:
#!/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()
在Java代码? Java代码工作正常。我从控制台运行它并获得预期的结果。问题在于python脚本。谢谢 – user60108 2013-05-08 23:33:58
是的,在Java代码中。写入终端时,所有进程都会应用不同的缓冲区。在写入管道(而不是tty)时,Java进程假定这是批量数据连接,并且只在缓冲区耗尽时才刷新。插入该冲洗并再试一次。 – Alfe 2013-05-08 23:40:50
我试过了,并没有成功。问题在于Python代码。我无法在java解释器中运行这些命令。谢谢 – user60108 2013-05-08 23:44:26