前几天在学习(Django)的时候发现了这问题,调用另一个py文件会报错,原因是未在他自己的目录下运行
然后做了很多修改
import subprocess
from django.http import JsonResponse
import os
import sys # 导入sys模块以获取当前Python解释器的路径
def run_detect_script_view(request):
# 获取detect.py脚本的绝对路径
script_dir = 'detection_recognition' # 根据实际情况调整路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
script_path = os.path.join(project_root, script_dir, 'detect_plate.py')
# 获取当前Python解释器的路径
python_interpreter = sys.executable
try:
# 执行脚本并指定其运行的工作目录
result = subprocess.run([python_interpreter, script_path], check=True, text=True, capture_output=True,
cwd=os.path.join(project_root, script_dir))
# 捕获输出
output = result.stdout
except subprocess.CalledProcessError as e:
# 如果脚本执行失败,捕获错误输出
output = e.stderr
# 将输出打印到控制台
print(output)
这里的代码是a.py里的内容,我要调用的是detect_plate,他的父目录是detection_recognition,换成你自己的即可
目录示意图:
detection_recognition/
detect_plate.py
a.py的父目录/
a.py
如有错误欢迎指正