我需要从Django shell中执行一个Python脚本。我试着:

./manage.py shell << my_script.py

但这并没有起作用。它只是在等我写点什么。


当前回答

正如其他答案所指出但没有明确指出的那样,你实际上需要的不一定是从Django shell中执行脚本,而是在不使用Django shell的情况下访问应用程序。

这在Django版本和Django版本之间有很大不同。如果你在这篇文章中没有找到你的解决方案,答案在这里—— Django脚本访问模型对象,而不使用manage.py shell ——或者类似的搜索可能对你有帮助。

我必须以my_command.py开始

import os,sys
sys.path.append('/path/to/myproject')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.file")
import django
django.setup()

import project.app.models
#do things with my models, yay

然后运行python3 my_command.py

(Django 2.0.2)

其他回答

@AtulVarma在不工作的接受答案下提供了一个非常有用的评论:

echo 'import myscript' | python manage.py shell

其实很简单,只要你打开django shell Python manage.py shell然后简单的写import test来导入test.py

# test.py
def x():
  print('hello');

现在您可以执行该文件中的命令

test.x() //  will print hello

注意,这个方法在django的最新版本中已经被弃用了!(> 1.3)

另一个答案是,您可以将它添加到my_script.py的顶部

from django.core.management import setup_environ
import settings
setup_environ(settings)

然后用python在settings。py目录下执行my_script.py,但这有点棘手。

$ python my_script.py

我刚刚发现一个有趣的东西是Django Scripts,它允许你用python manage.py runscript foobar来编写脚本。关于实现和结构的更多详细信息可以在这里找到,http://django-extensions.readthedocs.org/en/latest/index.html

另一种方式是执行这个

echo 'execfile("/path_to/myscript.py")' | python manage.py shell --settings=config.base

它在Python2.7和Django1.9上运行