2010-11-19 39 views
1

基本上,背后的故事是,我为客户端构建了一个Python脚本选择,用于处理在其操作数据库和其ecomms站点数据库之间导入和导出批处理作业。这工作正常。这些脚本写入标准输出以更新用户有关批处理脚本的状态。Django子过程从批处理脚本中生成/未生成stdout报告

我想要生成一个框架,这些脚本将通过Django视图运行,并将stdout发布到网页以向用户显示这些批处理过程的进度。

计划是 - 将批处理脚本作为子处理调用,然后将stdout和stderr保存到文件中。 - 将重定向返回到显示页面,该页面将每2秒重新加载一次,并逐行显示stdout正在写入的文件的内容。

然而,问题是,stdout/stderr文件没有被实际写入,直到整个批处理脚本完成运行或出错。

我已经尝试了一些东西,但似乎没有工作。

继承人当前的视图代码。

def long_running(app, filename): 
    """where app is ['command', 'arg1', 'arg2'] and filename is the file used for output""" 
    # where to write the result (something like /tmp/some-unique-id) 
    fullname = temppath+filename 
    f = file(fullname, "a+") 
    # launch the script which outputs something slowly 
    subprocess.Popen(app, stdout=f, stderr=f)# .communicate() 
    # once the script is done, close the output 
    f.close() 

def attributeexport(request): 
    filename = "%d_attribute" %(int(time.time())) #set the filename to be the current time stamp plus an identifier 
    app = ['python','/home/windsor/django/applications/attribute_exports.py'] 
    #break thread for processing. 
    threading.Thread(target=long_running, args=(app,filename)).start() 
    return HttpResponseRedirect('/scripts/dynamic/'+filename+'/') 
    pass 

def dynamic(request, viewfile): 
    fileobj = open(temppath+viewfile, 'r') 
    results = [] 
    for line in fileobj: 
     results.append(line) 
     if '~END' in line: 
      #if the process has completed 
      return render_to_response('scripts/static.html', {'displaylist':results, 'filename':viewfile}) 
    return render_to_response('scripts/dynamic.html', {'displaylist':results, 'filename':viewfile}) 
pass 
+0

你的问题是输出缓冲;这可能会帮助你,或者可能不会,因为你没有直接阅读输出:http://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess – eternicode 2010-11-19 06:26:34

+0

我想我可能不得不考虑处理通过原始脚本输出,设置关键点以保存更新的日志文件,并将文件名作为参数传递给原始脚本......我希望避免这样做,因为有很多这些脚本必须更改。 – BenDog 2010-11-22 05:02:32

回答

1

它帮助,如果您使用以下命令:

['python','-u','path/to/python/script.py'] 
+0

请注意,如果您需要autoreloader,则应该使用'PYTHONUNBUFFERED'环境变量,因为autoreloader不会将Python级别的CLI参数传递给子流程。 – Joe 2014-04-25 17:02:03