How to execute a Python script from the Django shell?

277

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.

This question is tagged with python django django-shell

~ Asked on 2013-05-31 09:05:36

The Best Answer is


437

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())

~ Answered on 2013-05-31 09:13:21


239

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

~ Answered on 2013-05-31 09:10:48


Most Viewed Questions: