11
votes

I'm trying to use Werkzeug in my Django project, which essentially is a web-page Python shell interface. I want to run commands such as python manage.py syncdb and python manage.py migrate but in the Python shell it isn't very straightforward.

I tried import manage and attempting commands from there, but from the looks of the source of manage.py, there's nothing to call, as it passes arguments to django.core.management.execute_from_command_line().

I also tried defining a function as shown "Running shell command from Python and capturing the output", but calling it using

runProcess('Python manage.py syncdb')

returns only:

<generator object runProcess at 0x000000000520D4C8>
2

2 Answers

19
votes

You could start a Django shell from the command line:

python manage.py shell

Then import execute_from_command_line:

from django.core.management import execute_from_command_line

And finally, you could execute the commands you need:

execute_from_command_line(["manage.py", "syncdb"])

It should solve your issue.

As an alternative, you could also take a look at the subprocess module documentation. You could execute a process and then check its output:

import subprocess
output = subprocess.check_output(["python", "manage.py", "syncdb"])
for line in output.split('\n'):
    # do something with line
1
votes

Note: this is for interactive usage, not something you could put in production code.

If you're using ipython, you can do

!python manage.py syncdb

The '!' says:

I want to execute this as if it is a shell command

If you have pip installed, you can get ipython with:

pip install ipython

which you would want to run at the command line (not in the Python interpreter). You might need to throw a sudo in front of that, depending on how your environment is set up.