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.

2/16/2018 11:54:33 AM

Accepted Answer

The << part is wrong, use < instead:

$ ./ shell <

You could also do:

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

For python3 you would need to use

>>> exec(open('').read())
6/22/2017 8:00:42 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow