2015-07-10 38 views
2

我想從我的Django應用程序內執行Python腳本。我試着從終端執行它,它工作正常,所以我知道被調用的Python腳本工作正常。 Python腳本調用覆蓋服務器上文件的外部程序。外部程序具有所有必需的權限。我甚至嘗試對涉及的所有文件使用777權限,但仍然沒有用。無法從django執行外部python腳本

Django的觀點:

import subprocess 
subprocess.call("python " + script_dir+"testScript.py", shell=True) 

的Python - 2.7

我可以執行簡單的命令,如

subprocess.call("rm " + script_dir+"test.txt", shell=True) 

編輯: 我不僅從終端執行Python腳本,我也需要執行一個混合器腳本,它本身再次正常工作(當直接從終端執行時),但不會從內部生成所需的輸出Django的。

這是錯誤在我的Django控制檯:

OSError at /getObj/ 

[Errno 2] No such file or directory 

Request Method:  GET 
Request URL: http://192.168.1.21:8081/getObj/?width=5.0&height=6.0&depth=7.0 
Django Version:  1.7.8 
Exception Type:  OSError 
Exception Value:  

[Errno 2] No such file or directory 

Exception Location:  /usr/lib/python2.7/subprocess.py in _execute_child, line 1327 
Python Executable: /usr/bin/python 
Python Version:  2.7.6 
+2

你爲什麼要通過'subprocess'調用Python腳本?爲什麼不導入它並直接調用它? –

+0

實際上我需要從Django應用程序運行3個腳本,其中2個腳本不是直接的python腳本。所以我需要使用子進程。雖然你確實有一點。 – ms95

+0

你得到的錯誤是什麼? – deathangel908

回答

1

首先,我建議通過導入它,而不是在一個單獨的進程中運行它(除非你有特殊的理由這樣做運行Python代碼那)。既然你提到了你想運行的其他非Python腳本,我會建議一種通用的方式。

我會嘗試和運行使用Popen這樣的腳本:

from subprocess import Popen, PIPE 

# ... 

p = Popen(["python", "testScript.py"], cwd=script_dir, stdout=PIPE, stderr=PIPE) 
out, err = p.communicate() 

然後,你必須在out標準輸出和標準錯誤輸出err。即使它沒有成功運行,在檢查這兩個變量之後,你仍然有一些工作要做。

+0

非常感謝!有效 :) – ms95