Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django开发服务器能否以编程方式启动?_Python_Django - Fatal编程技术网

Python Django开发服务器能否以编程方式启动?

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

我正试图从包中的另一个模块启动django开发服务器。我的模块可以导入manage.py,我希望在不使用子流程或任何类似的情况下执行与之等效的
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的模块