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.
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.
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
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
: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
and execute
my_script.py
just with python in the directory where you havesettings.py
but this is a bit hacky.django.setup() does not seem to work.
does not seem to be required either.
this alone worked.
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
to do this create a file in a subdir of
management
andcommands
of yourapp
, ieand 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
)