我需要从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

其他回答

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

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.setup()似乎不能正常工作。

似乎也不是必须的。

仅这一点就奏效了。

import os, django, glob, sys, shelve
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings")

如果你想执行启动脚本(例如,导入一些django模型来与它们交互工作),并保持在django shell中:

PYTHONSTARTUP=my_script.py python manage.py shell

如果IPython可用(pip install IPython),那么./manage.py shell将自动使用它的shell,然后你可以使用神奇的命令%run:

%run my_script.py

不建议你在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