Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取命令行脚本的输出作为模板变量_Python_Django - Fatal编程技术网

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

Python 获取命令行脚本的输出作为模板变量,python,django,Python,Django,我是django的新手,需要帮助 我有一个正常工作的应用程序(遗留),我正在尝试在dev机器中添加一个新页面,使其能够运行一些脚本,这样设计者就不必进行ssh登录 我希望它运行脚本并将其输出返回到html页面,因此我完成了以下操作: url.py: url(r'^DEVUpdate', 'myviewa.views.devUpdate'), 他认为: def devUpdate(request): response = os.popen('./update.sh').read()

我是django的新手,需要帮助

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

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

url.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 }}
Response:
在我的机器中,转到DEVUpdate页面时的输出为:

sh: 1: ./update.sh: not found
但在html中:

Response:
{{ response }}
Response:
如何在html中获取响应的值


PD:我想在html页面中看到消息“sh:1:./update.sh:not found”

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

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

现在,您尝试从模板访问响应,但无法在上下文中传递它。popen将在stdout上返回命令的输出。这样的错误消息将发送到stderr,因此您将无法获得它

此外,os.popen也不推荐使用,比如说。相反,请使用
子流程。检查\u输出

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给出响应之前完成。但这与问题无关。

udpate.sh的路径错误。你能发布目录结构吗?如果路径没有错误,内容是什么?shell脚本可能无法运行。路径错误,正确,但我想查看消息。/update.sh:在html页面中找不到它。ludn locals()不是这样做的吗?嗯。。。也许,坦白地说,我不知道,我从来没有使用过它,尽管明文传递应该永远不会起作用。令人恼火的是,当我打印本地人时,它会显示“响应”:“”。因此,我有响应变量,但没有值:(您可能希望添加脚本的完整路径应该被传递。我想他知道,他的问题是关于捕获响应变量中的错误。我指的是:
sh:1:./update.sh:not found
是的,这就是以这种方式结束的
response
的确切错误消息,它将显示在他的模板中。He不是在问如何修复它,就像冠军一样,谢谢。