How to execute a Python script from the Django shell? How to execute a Python script from the Django shell? python python

How to execute a Python script from the Django shell?


The << part is wrong, use < instead:

$ ./manage.py shell < myscript.py

You could also do:

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

For python3 you would need to use

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


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 BaseCommandclass Command(BaseCommand):    def handle(self, **options):        # now do the things that you want with your models here


For anyone using Django 1.7+, it seems that simply import the settings module is not enough.

After some digging, I found this Stack Overflow answer: https://stackoverflow.com/a/23241093

You now need to:

import os, djangoos.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")django.setup()# now your code can go here...

Without doing the above, I was getting a django.core.exceptions.AppRegistryNoReady error.

My script file is in the same directory as my django project (ie. in the same folder as manage.py)