python - 如何在 django shell 中重新加载模块?

标签 python django ipython

我正在使用 Django 并一直使用 Django shell。烦人的部分是,当 Django 服务器重新加载代码更改时,shell 不会,所以每次我对正在测试的方法进行更改时,我都需要退出 shell 并重新启动它,重新导入我的所有模块需要,重新初始化我需要的所有变量等。虽然 iPython 历史在这方面节省了很多打字,但这仍然很痛苦。有没有办法让 django shell 自动重新加载,就像 django 开发服务器一样?

我知道reload(),但是我导入了很多模型,一般使用from app.models import *语法,所以reload()帮不上什么忙。

最佳答案

我建议使用 IPython autoreload extension .

./manage.py shell

In [1]: %load_ext autoreload
In [2]: %autoreload 2

从现在开始,所有导入的模块都将在评估之前刷新。

In [3]: from x import print_something
In [4]: print_something()
Out[4]: 'Something'

 # Do changes in print_something method in x.py file.

In [5]: print_something()
Out[5]: 'Something else'

如果在 %load_ext autoreload 命令之前导入了某些内容,也可以使用。

./manage.py shell
In [1]: from x import print_something
In [2]: print_something()
Out[2]: 'Something'

 # Do changes in print_something method in x.py file.

In [3]: %load_ext autoreload
In [4]: %autoreload 2
In [5]: print_something()
Out[5]: 'Something else'

还可以使用 %aimport 命令和 3 个自动重载策略来阻止某些导入刷新:

%autoreload

  • Reload all modules (except those excluded by %aimport) automatically now.

%autoreload 0

  • Disable automatic reloading.

%autoreload 1

  • Reload all modules imported with %aimport every time before executing the Python code typed.

%autoreload 2

  • Reload all modules (except those excluded by %aimport) every time before executing the Python code typed.

%aimport

  • List modules which are to be automatically imported or not to be imported.

%aimport foo

  • Import module ‘foo’ and mark it to be autoreloaded for %autoreload 1

%aimport -foo

  • Mark module ‘foo’ to not be autoreloaded.

这通常适合我的使用,但有一些注意事项:

  • Replacing code objects does not always succeed: changing a @property in a class to an ordinary method or a method to a member variable can cause problems (but in old objects only).
  • Functions that are removed (eg. via monkey-patching) from a module before it is reloaded are not upgraded.
  • C extension modules cannot be reloaded, and so cannot be autoreloaded.

关于python - 如何在 django shell 中重新加载模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3772260/

相关文章:

python - 我试图将公司交易量的平均值与同一公司的每日交易量进行比较,并找出 pandas 的差异。我在公司上做了groupby

python - 我需要用一个链表实现实现一个稀疏数组

python - 呈现 : 'BoundField' object is not iterable 时捕获类型错误

python - Django/Python - 将数据收集到正确的形式(算法)

python - 通过 ORM 为日期添加天数

ipython - 有什么方法可以在编辑模式、Jupyter Notebook 中交换 Enter 和 Shift-Enter 输入命令?

python - 如何在 IPython 控制台中默认运行文件而不是终端?

Maya 中的 Python 文本字段

python - 如何使用 Spark Data Frame 中前一行的两列计算一行中的列?

python - 如何使用 iPython 进行解压?