[Answer]-Get the output of a command line script as a template variable

1👍

os.popen returns the output of the command on stdout. An error message like that goes to stderr, so you won’t get it.

Besides, os.popen is deprecated, as the docs say. Instead, use 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

Lastly, if update.sh takes more than a couple of seconds or so, it should probably be a background task called by Celery. Now the whole command has to finish before Django gives a response. But that’s not related to the question.

0👍

You need to pass response in context:

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

Right now you try to access response from template but you don’t pass it in context

Leave a comment