Django:'RUN_MAIN'环境变量的意义

问题描述 投票:2回答:2

发布管理命令runserver时,它使用加载程序运行服务器。在Django1.5的源代码中遇到了一段代码在新服务器/线程中启动服务器之前,如果不是RUN_MAIN

,则在环境变量中将'true'的值专门设置为'true'

django / utils / autoreload.py

 new_environ = os.environ.copy()
 new_environ["RUN_MAIN"] = 'true'
 exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ)

在另一段代码中,它检查该值是否设置为not,如果设置了,则仅创建一个新的进程/线程。

 if os.environ.get("RUN_MAIN") == "true":
        thread.start_new_thread(main_func, args, kwargs)

默认情况下,在system(linux2)中未设置该值。

查询:

1)该环境变量的意义是什么以及它与启动之间的关系新进程/线程。

2)如果"RUN_MAIN"为'true',则代码创建线程,否则创建进程。为什么会这样?

thread-safety django-1.5
2个回答
0
投票

我查看Django代码,然后我用Google搜索您的问题,错误无法回答。

我谈论我的想法。

first,在python_reloader函数中,RUN_MAIN未定义,因此运行restart_with_reloader函数。在restart_with_reloader中创建一个子进程,在子进程RUN_MAIN中为True。现在,父进程正在等待exit_code

python_reloader中的子进程启动服务器的新线程。接下来,子进程的主线程运行reloader_thread函数,当代码文件更改时,运行sys.exit(3),子进程退出,返回退出代码3。

父进程将在下一个循环中运行,创建另一个子进程,然后重新启动服务器。如果exit_code不等于3(例如,按'ctrl-c'),则restart_with_reloader函数中的父过程返回exit_code,代码运行结束。

我的英语太糟糕了,我希望你能理解。

def reloader_thread():
    while RUN_RELOADER:
        # waiting code change
        if code_changed():
            sys.exit(3) # force reload

def restart_with_reloader():
    while True:
        new_environ = os.environ.copy()
        new_environ["RUN_MAIN"] = 'true'
        # create a child process
        exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ)
        if exit_code != 3:
            # end
            return exit_code

def python_reloader(main_func, args, kwargs):
    if os.environ.get("RUN_MAIN") == "true":
        # new thread in child process
        thread.start_new_thread(main_func, args, kwargs)
        try:
            reloader_thread()
        except KeyboardInterrupt:
            pass
    else:
        try:
            exit_code = restart_with_reloader()
            if exit_code < 0:
                os.kill(os.getpid(), -exit_code)
            else:
                sys.exit(exit_code)
        except KeyboardInterrupt:
            pass

0
投票

答案:1)实际上,环境参数有助于管理许多过程。2)原因是自动重载(保存文件时)。

您将在这里了解该过程:

http://programmersought.com/article/49721374106/;jsessionid=766C1F404087AC1E369350A887C32A21

© www.soinside.com 2019 - 2024. All rights reserved.