How to execute a Python script from the Django shell?

user2429940 picture user2429940 · May 31, 2013 · Viewed 224.9k times · Source

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.

Answer

codeape picture codeape · May 31, 2013

The << part is wrong, use < instead:

$ ./manage.py shell < myscript.py

You could also do:

$ ./manage.py shell
...
>>> execfile('myscript.py')

For python3 you would need to use

>>> exec(open('myscript.py').read())