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

./manage.py shell << my_script.py

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


当前回答

注意,这个方法在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

其他回答

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

%run my_script.py
import os, sys, django
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.path.insert(0, os.getcwd())

django.setup()

迟到了。但这可能对某些人有帮助。

你只需要安装好脚本和django扩展。

只需运行django_extensions中可用的shell_plus,并导入您所编写的脚本。

如果你的脚本是scpt.py,并且它在foll文件夹中,你可以像下面这样运行脚本。

python manage.py shell_plus

然后在shell中导入脚本,如下所示。

>>> from fol import scpt

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

<<部分是错误的,用<代替:

$ ./manage.py shell < myscript.py

你还可以:

$ ./manage.py shell
...
>>> execfile('myscript.py')

对于python3,您需要使用

>>> exec(open('myscript.py').read())