Python Django教程重新加载模块

Python Django教程重新加载模块,python,django,Python,Django,我正在浏览Django教程 编辑类后,它会显示: Save these changes and start a new Python interactive shell by running python manage.py shell again: >>> from polls.models import Poll, Choice 有没有可能不退出shell就可以这样做?不,没有。对.py文件所做的每一次编辑都不会自动在shell中重新加载。如果你想拥有这种类型的功能,你

我正在浏览Django教程

编辑类后,它会显示:

Save these changes and start a new Python interactive shell by running python manage.py shell again:

>>> from polls.models import Poll, Choice

有没有可能不退出shell就可以这样做?

不,没有。对.py文件所做的每一次编辑都不会自动在shell中重新加载。如果你想拥有这种类型的功能,你必须使用


这就支持了你所追求的。

我不确定我是否同意另一个答案

Python有一个内置函数,从文档中可以看出:

重新加载以前导入的模块。参数必须是模块对象,因此它必须在导入之前已成功导入

如果您已经使用外部编辑器编辑了模块源文件,并且希望在不离开Python解释器的情况下试用新版本,那么这将非常有用。返回值是模块对象(与模块参数相同)

但是,您必须从轮询中执行
导入模型
,然后执行
模型。轮询
(因为它必须传递给实际模块而不是类)和
模型。在代码中选择

这样,在不离开shell的情况下,您就可以运行
reload(models)

编辑1: 如果您不必一直输入
模型。
您也可以输入自己的快捷方式

from polls import models as pm
pm.Poll
pm.Choice

reload(pm)

我有时会遇到这种情况。而且已经是了

没错,reload()是有效的。但同时,这不是一个非常方便的选择

>>> from polls.models import Poll, Choice
.... #Some changes are done to your polls/models.py file and saved

>>> Poll #gives you old model
>>> reload(polls.models) #Reload works at module level!
>>> from polls.models import Poll, Choice # import again from the reloaded module
>>> Poll #gives you new model
那怎么办

def reload_all():
    import sys
    module = type(sys) # this type has no name!
    for m in sys.modules.values():
        if isinstance(m, module):
            try:
                reload(m)
            except:
                pass
不过,不确定这是否有副作用