简体   繁体   中英

django: See the result of a python script in my webpage

I am developing a website using Django. I want to see the result of a python script on my webpage. And after some searching, I realized subprocess popen can help me. I am very new to Django so I searched for a complete code. 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. But it uses flask and I don't know what will be the replacement for it in Django.

Here is my view.py:(It doesn't work)

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.

Can it be easier if I use ajax?

Thanks!

First of all, if you need to get just script output use subprocess.check_output() function.

When you want to return json from django view, the JsonResponse is best match for you.

import subprocess
from django.http import JsonResponse

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM