How to run arbitrary code when starting django shell?

This question: Automatic import of models at startup Django shell contains answers explaining how to import models at startup using shell_plus, but there is no answer on how to run the code as a whole.

But is there an easy way to run a python script?

python manage.py shell [or shell_plus] --run=script.py 

I would run the script as if you typed all this when the shell started.

I understand that you can import things into the shell, but then they get stuck in the namespace.

I would suggest that ipython should have a way to run the script and then import its locals() into the toplevel namespace. In this case, you can just do %magic script.py , and we will stop just one step, and that will be fine.

Changing the way shell starts should be great - the main goal is to simply create a file that starts when the shell starts.

+7
source share
4 answers

Not sure if there is a flag that you can use, but if you have ipython installed, it should be as simple as:

ipython

Then, when you are at the command prompt:

run script.py

Then:

run manage.py shell

+1
source

You can create your own command, as shell_plus did: see the source of the shell_plus command to see how to do this. In this code, you can specify and run the file that must be executed before running the shell. Also useful is Django's documentation on creating custom commands .

+2
source

You can try using the PYTHONSTARTUP environment variable. Also try django-extensions: django-extensions

See the django-extensions / management / commands / shell_plus.py command.

From the source code for this command, I see that it respects the env variable PYTHONSTARTUP.

+2
source

shell_plus uses a limited form of IPython that does not handle its startup and configuration, which strikes most conventional attempts to run things when the django + ipython shell starts. You can switch it to use the full version, which will solve most problems.

Edit django_extensions / management / commands / shell_plus.py

delete:

 embed(user_ns=imported_objects) 

and replace it with:

 from IPython import start_ipython start_ipython(argv=[], user_ns=imported_objects) 

Then your python code in the startup directories will be loaded.

+1
source

All Articles