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>

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

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.
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 '!'.
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.