Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run arbitrary code when django shell starts?

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.

like image 555
fastmultiplication Avatar asked Jul 16 '12 07:07

fastmultiplication


People also ask

Which file execute first in Django?

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.


2 Answers

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.

like image 61
Simeon Visser Avatar answered Oct 12 '22 22:10

Simeon Visser


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.

like image 22
Alexander A.Sosnovskiy Avatar answered Oct 12 '22 22:10

Alexander A.Sosnovskiy