我有外壳脚本。其中有 :
./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
这是描述os.system()
:
在子外壳程序中执行命令(字符串)。这是通过调用标准C函数system()来实现的,并且具有相同的限制。sys.stdin等的更改不会反映在已执行命令的环境中。如果命令生成任何输出,它将被发送到解释器标准输出流。
这意味着您的外壳会打印{risk_of_disease":"2.122e-314"}
到标准输出。
至于os.system()
退货0
:
在Windows上,返回值是运行命令后系统外壳程序返回的值。该外壳程序由Windows环境变量COMSPEC给出:它通常是cmd.exe,它返回命令运行的退出状态。在使用非本机Shell的系统上,请查阅您的Shell文档。
因此,您的shell脚本的返回代码为,0
并将其分配给result
。因此,从技术上讲,您已经将结果存储在变量中。
@编辑:
要解决问题,您需要使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句