django 前端将子进程输出显示在浏览器窗口
我有一个用perl写的后台程序。这个程序会把一些配置推送到网络设备上。它会输出很多信息,我希望用户能看到程序运行的过程。到目前为止,这个过程很简单,因为我一直是在终端上运行。
现在我想写一个django应用。我基本上希望用户点击提交后,浏览器能带他们到一个新页面,而在这个新页面上,我想让用户看到这个程序运行时的文本输出。
我已经成功让程序在后台运行,使用的是:http://docs.python.org/library/subprocess.html
假设下面是一个简单的请求。在响应的网页上,我希望能实时看到程序的输出,或者至少每隔几秒刷新一下,看到最新的输出(这可能是目前的一个解决办法)。
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, } )
1 个回答
2
你可以这样读取子进程的输出...
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})
不过,你只能在这个进程结束后才能看到结果。如果你想在程序运行的时候就看到输出,那就有点复杂了。我想可以通过把子进程的调用放到一个单独的进程或线程中来实现,让这个进程把结果写到一个文件或者消息队列里,然后再从那个文件中读取内容来显示。