[英]Why does manage.py execution script run twice when using it under if __name__ == “__main__”
Goal. 目标。 When launching django framework also launch other PY scripts that rely on django objects.
启动django框架时,还要启动其他依赖django对象的PY脚本。 Get the server and port number from a config file.
从配置文件获取服务器和端口号。
Problem: The Popen seems to run twice and I'm not sure why? 问题:Popen似乎运行了两次,我不确定为什么吗?
#!/usr/bin/env python
import os
import sys
import subprocess
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test.localsettings")
from django.core.management import execute_from_command_line
def getargs():
try:
f = open("config")
data = []
for line in f:
data.append(line)
f.close()
server = data[0].rstrip()
port = data[1]
newargs = ['lmanage.py', 'runserver', server + ':' + port]
return newargs
except Exception as e:
print e
pass
if __name__ == "__main__":
#Launching Checker
try:
checker = subprocess.Popen([sys.executable, os.path.join(os.getcwd() + "checker.py")], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
print checker.pid
except Exception as e:
print e
pass
print "end"
execute_from_command_line(getargs())
Outputs: 输出:
16200
end
29716
end
Validating models...
This is my first attempt so if anyone knows of a better way to do this then feel free to let me know. 这是我的第一次尝试,因此,如果有人知道更好的方法,请随时告诉我。
Thanks everyone. 感谢大家。
Your code is launching the runserver
command, which causes Django to use the reloader , which in turn means that your code is reexecuted as if it were entered on the command line. 您的代码正在启动
runserver
命令,这将导致Django使用reloader ,这反过来意味着您的代码将像在命令行中输入的那样被重新执行。 If you use --noreload
when you launch runserver
the issue will disappear. 如果在启动
runserver
时使用--noreload
, runserver
此问题将消失。
So basically, the same facility that automatically reloads Django when you modify your source files, which is so useful in development, is now causing your code to execute twice. 因此,基本上,使用相同的工具在修改源文件时会自动重新加载Django(这在开发中非常有用),现在会导致您的代码执行两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.