2013-04-07 110 views
7

我正在嘗試在我的Django項目中使用Werkzeug,該項目基本上是一個網頁Python外殼界面。我想運行諸如python manage.py syncdbpython manage.py migrate的命令,但是在Python shell中它並不是非常簡單。如何從Python shell執行manage.py

我試過import manage並嘗試從那裏發出命令,但是從manage.py的源代碼看起來,沒有什麼可以調用的,因爲它將參數傳遞給django.core.management.execute_from_command_line()

我也試圖定義 「所示Running shell command from Python and capturing the output」 的功能,但使用

runProcess('Python manage.py syncdb') 

只返回調用它:

<generator object runProcess at 0x000000000520D4C8> 

回答

10

你可以開始從命令行運行Django shell:

python manage.py shell 

Then then execute_from_command_line

from django.core.management import execute_from_command_line 

最後,你可以執行你所需要的命令:

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

應該解決您的問題。

作爲替代方案,您也可以查看subprocess module documentation。您可以執行的過程,然後檢查其輸出:

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

This Works,thanks! – TreyENelson 2013-04-07 19:01:46

0

注:這是一個交互式的使用,不是你可以把在生產代碼。

如果您使用ipython,你可以做

!python manage.py syncdb 

的 '!'說:

我想執行這個,就好像它是一個shell命令

如果已經PIP安裝,你可以得到IPython的搭配:

pip install ipython 

,你會想在命令行運行(不在Python解釋器中)。您可能需要在前面投擲一個sudo,具體取決於您的環境設置方式。

+0

這將是理想的解決方案,但是在安裝ipython後,從python shell運行'!python manage.py syncdb'會在導入IPython之前和之後在'!'上返回語法錯誤。 – TreyENelson 2013-04-07 18:59:37

+0

你是不是用'python'啓動python shell?你會想要使用'ipython'。 ipython shell像python shell一樣工作,但是增加了一些功能,比如'!'。 – bgschiller 2013-04-07 22:50:15

+0

啊,有道理,但它並不能真正解決原始問題,因爲werkzeug使用普通的Python shell。 (除非我錯過了一些設置,可以指定使用ipython shell) – TreyENelson 2013-04-08 00:31:46