我需要从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 shell Python manage.py shell然后简单的写import test来导入test.py

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

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

test.x() //  will print hello

正如其他答案所指出但没有明确指出的那样,你实际上需要的不一定是从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)

从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上测试。

如果你正在使用虚拟环境,试试这个:-

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的最新版本中已经被弃用了!(> 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