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

./manage.py shell << my_script.py

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


当前回答

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

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

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

test.x() //  will print hello

其他回答

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

如果你想在BG中更好地磨合:

nohup echo 'exec(open("my_script.py").read())' | python manage.py shell &

输出将在noup .out中

我迟到了,但我希望我的回答能帮助到别人: 你可以在你的Python脚本中这样做:

import sys, os
sys.path.append('/path/to/your/django/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings

你的其他东西在这里....

如果你的脚本中没有很多命令,使用它:

manage.py shell --command="import django; print(django.__version__)"

Django文档在manage.py shell上

你可以使用DJANGO_SETTINGS_MODULE环境变量来运行脚本。这就是设置Django-shell环境所需的全部内容。

这在Django >= 1.4中是有效的