获取命令行脚本的输出作为模板变量

2024-04-25 18:48:49 发布

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

我刚来django,需要帮助。你知道吗

我有一个正常工作的应用程序(遗留),我正在尝试在dev machine中添加一个新页面,使其能够运行一些脚本,这样设计者就不必进行ssh登录。你知道吗

我希望它运行脚本并将其输出返回到html页面,因此我完成了以下操作:

你知道吗网址.py地址:

url(r'^DEVUpdate', 'myviewa.views.devUpdate'),

在视图中:

def devUpdate(request):
    response = os.popen('./update.sh').read()
    print response
    return render_to_response('aux/update.html', locals(), context_instance=RequestContext(request));

在html中:

Response:
{{ response }}

在我的机器中,转到DEVUpdate页面时的输出是:

sh: 1: ./update.sh: not found

但在html中:

Response:

如何在html中获得响应的值?你知道吗

PD:我想查看消息“sh:1:”/更新.sh:在html页中找不到


Tags: djangodev脚本应用程序responserequesthtmlsh
2条回答

os.popen返回stdout上命令的输出。像这样的错误消息会传到stderr,所以你不会得到它。你知道吗

除此之外,欧斯波本正如the docs所说的,它已被弃用。相反,使用subprocess.check_output

import subprocess

try:
    # stderr=subprocess.STDOUT combines stdout and stderr
    # shell=True is needed to let the shell search for the file
    # and give an error message, otherwise Python does it and
    # raises OSError if it doesn't exist.
    response = subprocess.check_output(
        "./update.sh", stderr=subprocess.STDOUT,
        shell=True)
except subprocess.CalledProcessError as e:
    # It returned an error status
    response = e.output

最后,如果update.sh花费的时间超过几秒钟左右,则可能是芹菜所称的后台任务。现在整个命令必须在Django给出响应之前完成。但这与问题无关。你知道吗

您需要在上下文中传递响应:

return render_to_response('aux/update.html', locals(), context_instance=RequestContext(request, {'response': response});

现在,您尝试从模板访问响应,但没有在上下文中传递它

相关问题 更多 >