I basically have a backend program written in perl. This program pushes some configuration onto a network device. It gives a lot of output and I want users to be able to see the program as it r开发者_如何学Pythonuns. Up to now this has been easy as I have been running from the terminal.
Now I am trying to write a django app. I basically want a user to press submit, the browser to bring them to a new page and on this new page I want the user to see the text output of that program as it runs.
I have managed to get the program running in the backgroound using: http://docs.python.org/library/subprocess.html
Say the below is a simple request. In the response webpage I want to see the output of the program running live or at least refresh to see the latest output every few seconds (might be a workaroudn for now)
def config(request):
builder_Config_list = Config.objects.all().order_by('-generated_date')[:100]
if 'hostname' in request.POST and request.POST['hostname']:
hostname = request.POST['hostname']
command = "path/to/builder.pl --router " + hostname
result = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
return render_to_response('config/config.html', {'result':result, } )
You can read the output of the subprocess like so...
pipe = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
result = pipe.stdout.read() # this is the output of the process
return render_to_response('config/config.html', {'result': result})
However, you will only be able to see the result after the process has finished. If you want to see the output as the program runs, that will be a bit tougher. I suppose it could be accomplished by putting the subprocess call into a separate process or thread, having the process write to a file or message queue, and then reading from that file in your view.
精彩评论