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>
To run a task of the manage.py utilityOn the main menu, choose Tools | Run manage.py task, or press Ctrl+Alt+R . The manage.py utility starts in its own console.
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!
When you run python manage.py shell you run a python (or IPython) interpreter but inside it load all your Django project configurations so you can execute commands against the database or any other resources that are available in your Django project.
python manage.py shell starts up a regular version of the python interrupter but with the added environment. For example try executing your statements in the regular python interrupter rather than the django shell.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With