Django开发服务器可以通过编程方式启动吗? [英] Can the Django development server be started programmatically?
问题描述
我正在尝试从程序包中的另一个模块启动django开发服务器.我的模块可以导入manage.py,并且我想执行 manage.py runserver
的等效项,而不使用子进程或类似的任何东西(为什么?请参见下文).
I'm trying to start the django development server from another module in my package. My module can import manage.py, and I want to execute the equivalent of manage.py runserver
without using subprocess or anything of that sort (why? see below).
目前我能想到的最好的解决方案是使用子进程:
Currently the best solution I could come up with is to use subprocess:
def run_with_default_settings():
import inspect
import subprocess
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
subprocess.Popen(['python', 'manage.py', 'runserver'], cwd=currentdir)
但是,在我看来,此解决方案似乎过于复杂,更重要的是,它不是独立于平台的(例如,如果某人同时拥有python 2和python 3,并且定义了 python
作为python 3;或者如果在环境PATH中未定义 python
等).
However this solution seems to me rather overcomplicated, and more importantly it is not platform independent (for example if someone has both python 2 and python 3 and python
is defined as python 3; or if python
is not defined in the environment PATH... etc.).
我无法在线找到任何解决方案,而我尝试运行 execute_from_command_line()
的每一种方法都失败了.
I couldn't find any solutions online, and every way I tried to run execute_from_command_line()
failed miserably.
有什么想法吗?
推荐答案
是.只需执行 manage.py
中的内容:
Yes. Just do what's in the manage.py
:
import os
from django.core.management import execute_from_command_line
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web.settings')
execute_from_command_line(list_of_args)
这应该可以正常工作.只需记住, execute_from_command_line
最初接受 sys.argv
作为参数,因此命令 runserver
位于索引 1 上:
This should work fine. Just remember that execute_from_command_line
accepts originally sys.argv
as argument, so the command runserver
is on the index 1:
list_of_args = ['', 'runserver']
这篇关于Django开发服务器可以通过编程方式启动吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!