Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

python - 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. Get the server and port number from a config file.

Problem: The Popen seems to run twice and I'm not sure why?

#!/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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. If you use --noreload when you launch runserver the issue will disappear.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...