我有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 :(得分:3)
Here是对os.system()
:
在子shell中执行命令(字符串)。这是通过调用标准C函数系统()来实现的,并且具有相同的限制。对sys.stdin等的更改不会反映在已执行命令的环境中。如果命令生成任何输出,它将被发送到解释器标准输出流。
这意味着,您的shell会将{risk_of_disease":"2.122e-314"}
打印到标准输出。
至于os.system()
返回0
:
在Windows上,返回值是运行命令后系统shell返回的值。 shell由Windows环境变量COMSPEC给出:它通常是cmd.exe,它返回命令运行的退出状态;在使用非本机shell的系统上,请参阅shell文档。
因此,您的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