为什么在 if __name__ == "__main__" 下使用 manage.py 执行脚本会运行两次

cph*_*cph 2 python django popen

目标。启动 django 框架时,也会启动其他依赖 django 对象的 PY 脚本。从配置文件中获取服务器和端口号。

问题: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())
Run Code Online (Sandbox Code Playgroud)

输出:

16200
end
29716
end
Validating models...
Run Code Online (Sandbox Code Playgroud)

这是我的第一次尝试,所以如果有人知道更好的方法,请随时告诉我。

谢谢大家。

Lou*_*uis 7

您的代码正在启动runserver命令,这会导致 Django 使用reloader,这反过来意味着您的代码被重新执行,就像在命令行中输入一样。如果您--noreload在启动时使用runserver该问题将消失。

所以基本上,当你修改源文件时自动重新加载 Django 的相同工具,这在开发中非常有用,现在导致你的代码执行两次。