Python Django开发服务器能否以编程方式启动?
我正试图从包中的另一个模块启动django开发服务器。我的模块可以导入manage.py,我希望在不使用子流程或任何类似的情况下执行与之等效的Python Django开发服务器能否以编程方式启动?,python,django,Python,Django,我正试图从包中的另一个模块启动django开发服务器。我的模块可以导入manage.py,我希望在不使用子流程或任何类似的情况下执行与之等效的manage.py runserver(为什么?请参见下文) 目前,我能想到的最佳解决方案是使用子流程: def run_with_default_settings(): import inspect import subprocess currentdir = os.path.dirname(os.path.abspath(ins
manage.py runserver
(为什么?请参见下文)
目前,我能想到的最佳解决方案是使用子流程:
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;或者如果python
未在环境路径中定义……等等)
我在网上找不到任何解决方案,每次尝试从命令行()运行execute\u时都失败了
有什么想法吗?有。只需执行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\u from_command\u line
最初接受sys.argv
作为参数,因此命令runserver
位于索引1上:
list_of_args = ['', 'runserver']
不幸的是,这只适用于导入模块位于manage.py
所在的同一目录中的情况,至少在我的情况下是这样。否则,所有django导入都会失败:文件“C:\Python27\lib\importlib\\uuuuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuu.py”,第37行,在import\uuuuuuuuuuuuu模块中(名称)ImportError:没有名为fitter.apps的模块