Skip to main content
 首页 » 编程设计

python之无法从 Django 执行外部 Python 脚本

2025年05月04日24lhb25

我正在尝试从我的 Django 应用程序中执行 Python 脚本。我尝试从终端执行它并且它工作正常,所以我知道调用的 Python 脚本工作正常。 Python 脚本调用覆盖服务器上文件的外部程序。外部程序具有所有必需的权限。我什至尝试对所有涉及的文件使用 777 权限,但仍然没有用。

Django View :

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

python - 2.7

我可以执行更简单的命令,比如

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

编辑: 我不仅从终端执行 python 脚本,我还需要执行一个 blender 脚本,它本身也能正常工作(当直接从终端执行时),但不会从 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 

请您参考如下方法:

首先,我建议通过导入来运行 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 中有标准错误输出。即使它没有成功运行,在检查这两个变量后您也可以使用一些东西。