我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
当前回答
<<部分是错误的,用<代替:
$ ./manage.py shell < myscript.py
你还可以:
$ ./manage.py shell
...
>>> execfile('myscript.py')
对于python3,您需要使用
>>> exec(open('myscript.py').read())
其他回答
你可以使用DJANGO_SETTINGS_MODULE环境变量来运行脚本。这就是设置Django-shell环境所需的全部内容。
这在Django >= 1.4中是有效的
从django-extensions运行脚本
python manage.py runscript scripty.py
一个示例script.py来测试它:
from django.contrib.auth.models import User
print(User.objects.values())
提及地址:http://django-extensions.readthedocs.io/en/latest/command_extensions.html,记录地址:
python manage.py runscript --help
还有一个教程。
在Django 1.9.6和Django -extensions 1.6.7上测试。
对于使用Django 1.7+的人来说,仅仅导入设置模块似乎是不够的。
经过一番挖掘,我找到了这个Stack Overflow的答案:https://stackoverflow.com/a/23241093
你现在需要:
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()
# now your code can go here...
没有做上面的事情,我得到了一个django.core.exceptions.AppRegistryNoReady错误。
我的脚本文件是在相同的目录,我的django项目(即。和manage.py在同一个文件夹中)
其实很简单,只要你打开django shell Python manage.py shell然后简单的写import test来导入test.py
# test.py
def x():
print('hello');
现在您可以执行该文件中的命令
test.x() // will print hello
如果你正在使用虚拟环境,试试这个:-
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是我的虚拟环境名称