2014-10-05 74 views
1

我試圖在單獨的進程中運行'runserver'(和testserver),並在服務器仍在運行時讀取主輸出(我想要做一些自動e2e測試)。 我無法設法將寫入stdout存儲到文件。我使用的Python 3.4和1.7的Django用Popen捕獲django runserver的stdout

from subprocess import Popen 
from time import sleep 
out = open('/tmp/o', 'w') 
p = Popen(['./manage.py', 'runserver'] , stdout = out) 
sleep(5) 
out.flush() 
p.terminate() 
p.wait() 
out.close() 
print(open('/tmp/o').read()) 
# stdout file is empty 

# Making sure the same command with stdout=None prints something 
Popen(['./manage.py', 'runserver']) 
# prints output as expected 
sleep(5) 
p.terminate() 
p.wait() 

我明明做錯事,但我無法找到的文檔或任何其他計算器問題的任何幫助。

感謝

米爾科

回答

3

,我發現我的答案在這裏: https://code.djangoproject.com/ticket/19593#comment:4

設置變量PYTHONUNBUFFERED修復該問題

env = dict(os.environ, **{'PYTHONUNBUFFERED':'1'}) 

out = open('/tmp/o', 'w') 
p = Popen(['./manage.py', 'runserver', '-v', '3'] , stdout = out, env = env) 
環境