python中从a.py文件调用b.py文件,并且使b.py文件运行目录在他自己的环境下(a.py与b.py不在同一目录下)

前几天在学习(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

如有错误欢迎指正

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值