2011-09-07 71 views
0

我有一個Java程序,它在ubuntu的特定端口上運行。在運行程序時,我需要從程序獲取輸出,並需要將其保存在日誌文件中。我使用nohub來運行他們當他們失敗時,我不知道他們爲什麼失敗。然後進程重新啓動nohub被覆蓋。我希望進程重新啓動並更新日誌文件,我可以在以後檢查它。目前我不知道它的狀態,它運行還是失敗。python進程封裝

我聽說使用python腳本很容易做到這一點。 任何人都可以幫助我做到這一點?

在此先感謝 Renjith拉吉

回答

1

您應該使用subprocess模塊蟒蛇。 如果你的日誌是不是太大了,你可以簡單地使用:

# for python >=2.7 
result = subprocess.check_output(["/path/to/process_to_lauch", "arg1"]) 

# for python < 2.7 
process = subprocess.Popen(["/path/to/process_to_lauch", "arg1"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
str_out, str_errr = process.communicate() 
# in str_out you will find the standard output of your process 
# in str_err you will find the standard output of your process 

但如果你的輸出是真正的大(讓我們來談談在莫,而不是在KO),這可能會導致一些內存溢出... 在產量大的情況下,使用文件句柄輸出和錯誤:

out_file = open(out_file_name, "w") 
err_file = open(out_file_name, "w") 
process = subprocess.Popen(["/path/to/process_to_lauch", "arg1"], stdout=out_file, stderr=err_file) 
return_code = process.wait() 
out_file.close() 
err_file.close() 

,然後在out_file你會發現過程的輸出,並在err_file錯誤輸出。

當然,如果你想重新啓動它的過程時,把這個代碼放在一個循環;)