我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
当前回答
你可以简单地运行:
Python manage.py shell < your_script.py
它应该做到这一点!
其他回答
import os, sys, django
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.path.insert(0, os.getcwd())
django.setup()
不建议你在shell中这样做——这是因为你不应该在django环境中执行随机脚本(但是有一些方法可以解决这个问题,参见其他答案)。
如果这是一个脚本,你将运行多次,这是一个好主意设置为一个自定义命令,即
$ ./manage.py my_command
要做到这一点,在你的应用程序的管理和命令的子目录中创建一个文件
my_app/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
my_command.py
tests.py
views.py
并在该文件中定义您的自定义命令(确保文件的名称是您想要从。/manage.py执行的命令的名称)
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, **options):
# now do the things that you want with your models here
从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 Scripts,它允许你用python manage.py runscript foobar来编写脚本。关于实现和结构的更多详细信息可以在这里找到,http://django-extensions.readthedocs.org/en/latest/index.html
如果你想执行启动脚本(例如,导入一些django模型来与它们交互工作),并保持在django shell中:
PYTHONSTARTUP=my_script.py python manage.py shell