从python脚本执行来自另一个程序的命令

时间:2013-05-08 23:22:23

标签: java python input console communication

无法使用java程序从python脚本进行通信。 我有一个从标准输入读取的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 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()行破坏了脚本,我可以解决这个问题吗?

非常感谢你的任何帮助。

1 个答案:

答案 0 :(得分:1)

仅打印一个System.out后,即可刷新result

另外更改代码以执行此操作:

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()
相关问题