我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
当前回答
如果IPython可用(pip install IPython),那么./manage.py shell将自动使用它的shell,然后你可以使用神奇的命令%run:
%run my_script.py
其他回答
迟到了。但这可能对某些人有帮助。
你只需要安装好脚本和django扩展。
只需运行django_extensions中可用的shell_plus,并导入您所编写的脚本。
如果你的脚本是scpt.py,并且它在foll文件夹中,你可以像下面这样运行脚本。
python manage.py shell_plus
然后在shell中导入脚本,如下所示。
>>> from fol import scpt
如果你正在使用虚拟环境,试试这个:-
Python manage.py shell
要使用这些命令,您必须在虚拟环境中。本用途:-
被vir_env_name
例如:-
dc@dc-comp-4:~/mysite$ workon jango
(jango)dc@dc-comp-4:~/mysite$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
注意:这里mysite是我的网站名称,jango是我的虚拟环境名称
我刚刚发现一个有趣的东西是Django Scripts,它允许你用python manage.py runscript foobar来编写脚本。关于实现和结构的更多详细信息可以在这里找到,http://django-extensions.readthedocs.org/en/latest/index.html
@AtulVarma在不工作的接受答案下提供了一个非常有用的评论:
echo 'import myscript' | python manage.py shell
如果你想执行启动脚本(例如,导入一些django模型来与它们交互工作),并保持在django shell中:
PYTHONSTARTUP=my_script.py python manage.py shell