11

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>
Community
  • 1
  • 1
Saik
  • 305
  • 3
  • 11

2 Answers2

20

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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Valdir Stumm Junior
  • 4,568
  • 1
  • 23
  • 31
1

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
bgschiller
  • 2,087
  • 1
  • 16
  • 30
  • This would be the ideal solution, but after installing ipython, running `!python manage.py syncdb` from the python shell returns a syntax error on the `!`, before and after importing IPython. – Saik Apr 07 '13 at 18:59
  • are you starting the python shell with 'python' still? You will want to use 'ipython'. The ipython shell works just like the python shell, but with a few added features, such as the '!'. – bgschiller Apr 07 '13 at 22:50
  • Ah, makes sense, but it doesn't really solve the original problem, since werkzeug uses the normal Python shell. (Unless there's some setting I missed that lets you specify to use the ipython shell) – Saik Apr 08 '13 at 00:31