django:在我的网页中查看python脚本的结果

时间:2018-08-19 08:39:07

标签: python ajax django popen

我正在使用Django开发网站。我想在网页上查看python脚本的结果。经过一番搜索,我意识到子流程popen可以为我提供帮助。我对Django非常陌生,因此我搜索了完整的代码。我找到这些行:

output = None
    cmd = 'python ' + session["file_name"]
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
    output = p.stdout.read()

return jsonify(output.decode('utf-8'))

来自PythonBuddy开源代码。但是它使用了flask,但我不知道在Django中它将替代什么。

这是我的view.py :(不起作用)

output = None
def home(request):
    p = subprocess.Popen(["python","adoptions/executer.py"], close_fds=True)
    std_out, std_error = p.communicate()
    return jsonify(output.decode('utf-8'))

executer.py中的python代码是一个游戏,不像要打印的字符串,所以我发现很多代码都没用。

如果我使用ajax会更容易吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

首先,如果只需要获取脚本输出,请使用subprocess.check_output()函数。

当您想从Django视图返回json时,JsonResponse最适合您。

import subprocess
from django.http import JsonResponse

def home(request):
    output = subprocess.check_output(["python","adoptions/executer.py"])
    return JsonResponse(output)