django shell启动时如何运行任意代码?

fas*_*ion 7 python django debugging django-shell

这个问题:在Django shell启动时自动导入模型的答案解释了如何在开始时使用shell_plus导入模型,但没有回答如何一般地运行代码.

但有没有一种简单的方法来运行python脚本?

python manage.py shell [or shell_plus] --run=script.py
Run Code Online (Sandbox Code Playgroud)

只需运行脚本就像在shell启动时输入整个内容一样.

我意识到你可以在shell中导入东西,但是它们会被卡在命名空间中.

我认为ipython应该有办法运行脚本,然后将其locals()导入到顶级命名空间.在那种情况下你可以做到%magic script.py,我们只需要一步,这将是好的.

改变你启动shell的方式应该没问题 - 主要目标是能够创建一个在shell启动时运行的文件.

Ran*_* Ma 1

不确定是否有可以使用的标志,但如果安装了 ipython,它应该像以下一样简单:

ipython

然后当您出现提示时:

run script.py

然后:

run manage.py shell