This question: Automatically import models on Django shell launch has answers explaining how to import models upon start by using shell_plus, but no answer about how to run code in general.
But is there an easy way to just run a python script?
python manage.py shell [or shell_plus] --run=script.py
Would just run the script as if you'd typed the whole thing in as the shell started.
I realize that you can import things in the shell, but then they're stuck within a namespace.
I would think ipython should have a way to run a script, and then import its locals()
into the toplevel namespace. In that case you could just do %magic script.py
and we'd be down to just one step, which would be good.
Changing the way you start the shell should be fine - the main goal is to just be able to create a file that's run on startup of the shell.
The number one answer does not seem to work anymore, urls.py is loaded upon first request. When using ./manage.py runserver ... this gets executed twice, but that is because runserver has some tricks to validate the models first etc ... normal deployments or even when runserver auto reloads, this is only executed once.
You can create your own custom command just like shell_plus
has done: see the source of the shell_plus
command to see how. In that code you can specify and run the file that needs to be executed before starting the shell. Also useful is Django's documentation on creating custom commands.
You can try to use environment variable PYTHONSTARTUP. Also try django-extensions: django-extensions
See django-extensions/management/commands/shell_plus.py command.
From source code of this command I see that it respects PYTHONSTARTUP env variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With