基本上,背後的故事是,我爲客戶端構建了一個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
你的問題是輸出緩衝;這可能會幫助你,或者可能不會,因爲你沒有直接閱讀輸出:http://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess – eternicode 2010-11-19 06:26:34
我想我可能不得不考慮處理通過原始腳本輸出,設置關鍵點以保存更新的日誌文件,並將文件名作爲參數傳遞給原始腳本......我希望避免這樣做,因爲有很多這些腳本必須更改。 – BenDog 2010-11-22 05:02:32