2013-05-08 144 views
0

無法使用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()破壞腳本,因爲我可以修復這個?

非常感謝你的幫助。

回答

1

在打印一個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() 
+0

在Java代碼? Java代碼工作正常。我從控制檯運行它並獲得預期的結果。問題在於python腳本。謝謝 – user60108 2013-05-08 23:33:58

+0

是的,在Java代碼中。寫入終端時,所有進程都會應用不同的緩衝區。在寫入管道(而不是tty)時,Java進程假定這是批量數據連接,並且只在緩衝區耗盡時才刷新。插入該沖洗並再試一次。 – Alfe 2013-05-08 23:40:50

+0

我試過了,並沒有成功。問題在於Python代碼。我無法在java解釋器中運行這些命令。謝謝 – user60108 2013-05-08 23:44:26