gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:35:55 27 4
gpt4 key购买 nike

我正在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com