将shell脚本执行结果分配给variab

2024-05-08 01:42:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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脚本,并将结果存储到某个变量中。测试.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

Tags: inpyimport脚本cmdjsonoutputsh
1条回答
网友
1楼 · 发布于 2024-05-08 01:42:54

Hereos.system()的描述:

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。所以从技术上讲,您已经将结果存储在变量中了。你知道吗

@编辑:

要解决这个问题,您需要使用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

相关问题 更多 >