2012-08-01 36 views
2

我明白這個問題之前已經被問過,但建議的方法不適用於我。 這是我想從我的Django的觀點做:從Django的意見中運行Python文件

sudo python mypythonscript.py arg1 arg2 > mypythonscript.log 

如果我執行這個命令行它就像一個魅力,但不能讓它通過Django的視圖的工作。 我試過使用os.system(command)和subprocess.call(command,shell = True),但它們不起作用。 在此先感謝。

編輯: 這是我的views.py:

from django.http import HttpResponse 
import datetime 
import subprocess 

def li_view(request): 
if request.is_ajax(): 
     if request.method == 'GET': 
      message = "This is an XHR GET request" 
     elif request.method == 'POST': 
      message = "This is an XHR POST request" 
      print request.POST 
    else: 
     message = "No XHR" 
    num_instances = request.POST['num_instances'] 
    ami_id = "ami-ff02058b" 
    command = "sudo python /home/bitnami/launch_instances.py 1 " + num_instances + " " + ami_id + " > /home/bitnami/launcinstances.log" 
    subprocess.call(commad, shell=True) 
    return HttpResponse("something creative will go here later") 

整個故事是,我有我的網站上填寫表單,我想這種形式的內容arguements傳遞給我的launch_instances.py腳本。 當我按下我的表單中的提交按鈕時,它會發送到/ luanch_instances /,它將'重定向到'該視圖。 按照原樣執行代碼將不會執行任何操作,它只會在新頁面上向我顯示「稍後將創建一些內容」。 如果我是怎麼過使用

suprocess.check_call(command, shell=True) 

這就是我得到:

Command 'sudo python /home/bitnami/launch_instances.py 1 ami-ff02058b > /home/bitnami/launchinstances.log' returned non-zero exit status 2 
+3

您需要告訴我們爲什麼它沒有工作。顯示你的代碼和輸出。 – 2012-08-01 08:26:06

+2

另外你想通過在python視圖中做到這一點來完成什麼?通常最好使用諸如Celery這樣的任務隊列來執行這種事情,因爲它不會捆綁你的Web服務器。 – 2012-08-01 08:32:51

+0

@VladimirVolodin我已經添加了輸出和代碼 – AmirHBP 2012-08-01 08:48:17

回答

2

當你試圖運行Python腳本,你可以簡單地從launch_instances.py導入代碼到您的看法,將輸出重定向到/home/bitnami/launcinstances.log(關於將stdout重定向到python中的文件:Redirect stdout to a file in Python?)。但是root權限仍然存在問題 - 一種選擇是更改以下權限:從launch_instances.py調用代碼所需的資源;你的日誌文件;爲了讓你的django進程執行,第二個選項(不推薦)是以root身份運行django應用程序。

+0

我不知道爲什麼要執行:sudo python mypythonscript.py arg1 arg2> mypythonscript.log需要root權限。假設mypythonscript.py不是由django進程的所有者擁有,那麼你可以簡單地做chmod a + rx mypythonscript.pl – Marek 2012-08-01 09:26:54

+0

非常感謝你的隊友 – AmirHBP 2012-08-01 10:39:06

+0

但是記住做chmod a + rx可能會破壞安全性。 – Marek 2012-08-01 10:45:22

3

很可能它與權限有關。嘗試檢查命令執行的stderr和stdout。我正在使用此代碼來調試我的外殼命令:

process = subprocess.Popen(shlex.split(command), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
     output,error = process.communicate(input=pipe) 
+0

假設通過輸入=管你的意思輸入= subprocess.PIPE,我得到followng錯誤:'int'對象沒有屬性'__getitem__' – AmirHBP 2012-08-01 09:11:47