2014-05-06 19 views
0

我嘗試在我的java程序中運行python腳本。我想要做的就是捕獲python程序的exitValue,並通過System.out.println out寫出來。Java Processbuilder - 捕獲另一個腳本的退出值?

這裏是Python代碼:

import sys 
import subprocess 
print "hallo" 
i = sys.argv[0] 
path = "R:\\xxx\\xxx\\xxx\\read" 
resultlist = [] 

if i == 0: 
    result = True 
else: 
    result = False 

resultlist.append(result) 
resultlist.append(path) 
sys.exit(resultlist) 

的方法的ProcessBuilder .waitFor()和.exitValue()只是給出一個0或1分的。所以我不能使用它。

是否有任何可能的方法從我的java程序中的python腳本中捕獲sys.exit(resultlist)的值/字符串?

+0

呃,當然不是; exit()的結果是一個整數。您的使用被破壞,以 – fge

+0

開頭這不完全正確,通過cmd正常運行腳本我得到應該出來的全文(resultlist)。 – Jagson

+0

然後,這是一個蟒蛇技巧;但不能依賴。 – fge

回答

0

man 2 exit

The function _exit() terminates the calling process "immediately". Any open file descriptors belonging to the process are closed; any children of the process 
are inherited by process 1, init, and the process's parent is sent a SIGCHLD signal. 

**The value status is returned to the parent process as the process's exit status, and can be collected using one of the wait(2) family of calls.** 

您不能返回的 「複雜值」 與exit(2)(系統調用)開始。如果python這樣做很好,但這是一個「竅門」。不要依賴它。

你想要做的是打印你的程序輸出到標準輸出和捕獲標準輸出。爲此,請使用Process.getInputStream()並將其吞入,例如ByteArrayOutputStream

由於您使用ProcessBuilder,因此在執行過程之前,您還可以使用其.redirectOutput()方法。自Java 7以來,它有quite a few options available

相關問題