我试图运行' runserver' (和testserver)在一个单独的进程中,并在服务器仍在运行时读取main中的输出(我想做一些自动e2e测试)。 我无法将write stdout存储到文件中。我使用的是python 3.4和django 1.7
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()
我显然做错了什么,但我无法在文档或任何其他stackoverflow问题中找到任何帮助。
谢谢
的Mirko
答案 0 :(得分: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)