[英]django: See the result of a python script in my webpage
I am developing a website using Django. 我正在使用Django开发网站。 I want to see the result of a python script on my webpage.
我想在网页上查看python脚本的结果。 And after some searching, I realized subprocess popen can help me.
经过一番搜索,我意识到子流程popen可以为我提供帮助。 I am very new to Django so I searched for a complete code.
我对Django非常陌生,因此我搜索了完整的代码。 I find these lines:
我发现这些行:
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'))
from PythonBuddy opensource code. 来自PythonBuddy开源代码。 But it uses flask and I don't know what will be the replacement for it in Django.
但是它使用了flask,但我不知道在Django中它将替代什么。
Here is my view.py:(It doesn't work) 这是我的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'))
The python code in executer.py is a game, not something like a string to print, so many codes I found was useless. executer.py中的python代码是一个游戏,不像要打印的字符串那样,所以我发现很多代码都没有用。
Can it be easier if I use ajax? 如果我使用ajax会更容易吗?
Thanks! 谢谢!
First of all, if you need to get just script output use subprocess.check_output()
function. 首先,如果只需要获取脚本输出,请使用
subprocess.check_output()
函数。
When you want to return json from django view, the JsonResponse is best match for you. 当您想从Django视图返回json时,JsonResponse最适合您。
import subprocess
from django.http import JsonResponse
def home(request):
output = subprocess.check_output(["python","adoptions/executer.py"])
return JsonResponse(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.