2016-12-01 52 views
0

我有shell腳本。其中有:分配shell腳本執行結果給變量

./dtapi get_probability decision_tree simulated_diabetes_incidence_data_new.txt AGE 70 weight 34 height 5.5 sex 0 ds1 34 

現在我試圖用python腳本執行此shell腳本並將結果存儲到某個變量中。 test.py包含 -

import os, sys 
result = os.system("sh cmd_dtapi.sh") 
print "Result is : ", result 

但它的行爲是這樣的:

python test.py 
{"risk_of_disease":"2.122e-314"}Result is : 0 

結果得到直接打印,分配需要0

如何將結果存儲到某個變量中?

更新

以下的答案後 -

import subprocess 
import json 
result_process_output = subprocess.check_output("sh cmd_dtapi.sh") 
result_json = json.loads(result_process_output) 
result = result_json["risk_of_disease"] 
print "Result is : ", result  

給人

Traceback (most recent call last): 
    File "test.py", line 3, in <module> 
    result_process_output = subprocess.check_output("sh cmd_dtapi.sh") 
    File "/usr/lib/python2.7/subprocess.py", line 566, in check_output 
    process = Popen(stdout=PIPE, *popenargs, **kwargs) 
    File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ 
    errread, errwrite) 
    File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child 
    raise child_exception 
OSError: [Errno 2] No such file or directory 
+0

的面貌邁向子模塊http://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output https://docs.python.org/ 2/library/subprocess.html –

回答

3

Hereos.system() despcription:

Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream.

這意味着,您的shell將{risk_of_disease":"2.122e-314"}打印到標準輸出。

至於os.system()返回0

On Windows, the return value is that returned by the system shell after running command. The shell is given by the Windows environment variable COMSPEC: it is usually cmd.exe, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

所以回你的shell腳本的代碼爲0,並將其分配給result。所以技術上你已經將結果存儲在變量中。

@edit:

要解決問題,你需要使用subprocess模塊,它允許系統調用的更詳細的操作。

import subprocess 
import json 
result_process_output = subprocess.check_output("sh cmd_dtapi.sh", shell=True) 
result_json = json.loads(result_process_output) 
result = result_json["risk_of_disease"] 
print "Result is : ", result 
+0

它描述了'os.system',但它不能解決問題。 – furas

+0

@furas這似乎是正確的決議? –

+0

@TomaszPlaskota:我正在使用'python 2.7.6'。當我嘗試它時,我得到了'OSError:[Errno 2]沒有這樣的文件或目錄全問題追蹤 – user123