0

无法从 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 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() 行破坏了脚本,因为我可以解决这个问题吗?

非常感谢您的任何帮助。

4

1 回答 1

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()
于 2013-05-08T23:30:07.673 回答