2014-11-06 104 views
0

我是django的新手,需要幫助。獲取命令行腳本的輸出作爲模板變量

我有一個工作的應用程序(遺留),我想在開發機器上添加一個新頁面來運行一些腳本,以便設計人員不必做ssh登錄。

我希望它運行的腳本,並返回它的輸出到HTML頁面,所以我這樣做:

url.py:

url(r'^DEVUpdate', 'myviewa.views.devUpdate'), 

在視圖:

def devUpdate(request): 
    response = os.popen('./update.sh').read() 
    print response 
    return render_to_response('aux/update.html', locals(), context_instance=RequestContext(request)); 

而在HTML:

Response: 
{{ response }} 

當我去DEVUpdate頁面,在我的機器的輸出:

sh: 1: ./update.sh: not found 

,但在html:

Response: 

我如何在HTML響應的價值?

PD:我想看到消息 'SH:1:./update.sh:未發現' 在HTML頁面中

+1

udpate.sh的路徑錯誤。 – 2014-11-06 10:31:40

+0

你可以發佈目錄結構嗎? – 2014-11-06 10:32:24

+0

如果路徑沒有錯,內容是什麼? shell腳本可能無法運行。 – 2014-11-06 10:32:37

回答

1

os.popen返回標準輸出上的命令輸出。像這樣的錯誤消息發送到stderr,所以你不會得到它。

此外,os.popen已棄用,如the docs所述。相反,使用subprocess.check_output

import subprocess 

try: 
    # stderr=subprocess.STDOUT combines stdout and stderr 
    # shell=True is needed to let the shell search for the file 
    # and give an error message, otherwise Python does it and 
    # raises OSError if it doesn't exist. 
    response = subprocess.check_output(
     "./update.sh", stderr=subprocess.STDOUT, 
     shell=True) 
except subprocess.CalledProcessError as e: 
    # It returned an error status 
    response = e.output 

最後,如果update.sh時間超過幾秒鐘或這麼多,這也許應該是由芹菜稱爲後臺任務。現在,在Django作出迴應之前,整個命令必須完成。但這與問題無關。

+0

你可能想補充一點,應該傳遞腳本的完整路徑 – 2014-11-06 10:46:27

+1

我認爲他知道,他的問題是關於捕獲響應變量中的錯誤 – RemcoGerlich 2014-11-06 10:47:31

+0

我指的是:'sh:1:./update.sh:not found' – 2014-11-06 10:48:03

0

您需要通過上下文響應:

return render_to_response('aux/update.html', locals(), context_instance=RequestContext(request, {'response': response}); 

權現在您嘗試訪問模板的響應,但您不通過上下文

+0

sholudn't locals()這樣做嗎? – inigoD 2014-11-06 10:35:02

+0

好吧......也許,坦率地說,我不知道,我從來沒有使用它,雖然通過明確應該工作 – 4rlekin 2014-11-06 10:36:21

+0

令人討厭的是,當我做一個當地人打印()它顯示'響應': ''。所以,我有響應變量,但不是值:( – inigoD 2014-11-06 10:42:35