How to execute a Python script from the Django shell?


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

./ shell <<

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


The << part is wrong, use < instead:

$ ./ shell <

You could also do:

$ ./ shell
>>> execfile('')

For python3 you would need to use

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

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


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

 $ ./ my_command

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


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 ./

from 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: