How to execute a Python script from the Django she

2019-01-04 15:53发布

I need to execute a Python script from the Django shell. I tried:

./manage.py shell << my_script.py

But it didn't work. It was just waiting for me to write something.

16条回答
狗以群分
2楼-- · 2019-01-04 16:02
import os, sys, django
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.path.insert(0, os.getcwd())

django.setup()
查看更多
可以哭但决不认输i
3楼-- · 2019-01-04 16:07

You can just run the script with the DJANGO_SETTINGS_MODULE environment variable set. That's all it takes to set up Django-shell environment.

This works in Django >= 1.4

查看更多
Evening l夕情丶
4楼-- · 2019-01-04 16:07

If IPython is available (pip install ipython) then ./manage.py shell will automatically use it's shell and then you can use the magic command %run:

%run my_script.py
查看更多
孤傲高冷的网名
5楼-- · 2019-01-04 16:07

Note, this method has been deprecated for more recent versions of django! (> 1.3)

An alternative answer, you could add this to the top of my_script.py

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

and execute my_script.py just with python in the directory where you have settings.py but this is a bit hacky.

$ python my_script.py
查看更多
贼婆χ
6楼-- · 2019-01-04 16:07

django.setup() does not seem to work.

does not seem to be required either.

this alone worked.

import os, django, glob, sys, shelve
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings")
查看更多
聊天终结者
7楼-- · 2019-01-04 16:08

You're not recommended to do that from the shell - and this is intended as you shouldn't really be executing random scripts from the django environment (but there are ways around this, see the other answers).

If this is a script that you will be running multiple times, it's a good idea to set it up as a custom command ie

 $ ./manage.py my_command

to do this create a file in a subdir of management and commands of your app, ie

my_app/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            my_command.py
    tests.py
    views.py

and in this file define your custom command (ensuring that the name of the file is the name of the command you want to execute from ./manage.py)

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle_noargs(self, **options):
        # now do the things that you want with your models here
查看更多
登录 后发表回答