pythondjangodebuggingdjango-shell

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.


Solution

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

    ipython

    Then when you're in the prompt:

    run script.py

    Then:

    run manage.py shell