2017-04-09 80 views
0

我想从包中的另一个模块启动django开发服务器。我的模块可以导入manage.py,并且我希望执行manage.py runserver的等效命令,而不使用子进程或其他任何类型(为什么?请参见下文)。Django开发服务器是否可以以编程方式启动?

目前我能想出的最好的解决方案是使用子:

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未在环境PATH中定义...等)。

我在网上找不到任何解决方案,并且我试图运行execute_from_command_line()的每种方式都失败了。

任何想法?

回答

0

是的。只是做什么在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是对指数:

list_of_args = ['', 'runserver'] 
+0

不幸的是这仅适用,至少在我的情况下,如果导入模块在同一个目录中'manage.py'驻留。否则,所有django导入都会失败: “File”C:\ Python27 \ lib \ importlib \ __ init__.py“,第37行,位于import_module __import __(名称) ImportError:没有名为fitter.apps的模块 –

相关问题