How to execute manage.py command from Python shell

I am trying to use Werkzeug in my Django project, which is essentially a Python shell interface on a web page. I want to run commands like python manage.py syncdb and python manage.py migrate , but in the Python shell this is not very simple.

I tried import manage and tried to execute the commands from there, but there is nothing to call from the appearance of the source manage.py, since it passes the arguments django.core.management.execute_from_command_line() .

I also tried to define a function, as shown in โ€œ Running a Shell Command from Python and Capturing Output โ€, but calling it using

 runProcess('Python manage.py syncdb') 

returns only:

 <generator object runProcess at 0x000000000520D4C8> 
+7
source share
2 answers

You can start the 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 can execute the necessary commands:

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

It should solve your problem.

Alternatively, you can also take a look at the documentation of the subprocess module . You can execute the 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 
+10
source

Note: this is for interactive use, and not so that you can enter the production code.

If you are using ipython you can do

 !python manage.py syncdb 

"!" He speaks:

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

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

 pip install ipython 

which you want to run on the command line (not in the Python interpreter). You may need to quit sudo before this, depending on how your environment is configured.

0
source

All Articles