如何从Python3.11直接调用Python3.8环境中的PaddleOCR函数?
从Python 3.11直接调用Python 3.8环境中的PaddleOCR函数
以下是几种无需搭建Web API的直接实现方式:
方案一:子进程调用Python 3.8脚本
这是最轻量化的实现方式,通过命令行参数传递输入,标准输出传递结果,无额外依赖。
步骤1:编写Python 3.8环境的OCR封装脚本
创建paddle_ocr_wrapper.py,封装PaddleOCR的调用逻辑并序列化结果:
import json from paddleocr import PaddleOCR def ocr_image(image_path): ocr = PaddleOCR(use_angle_cls=True, lang='ch') result = ocr.ocr(image_path, cls=True) # 转换为JSON可序列化格式 serialized_result = [] for line in result: serialized_line = [[list(box) for box in line[0]], line[1][0], line[1][1]] serialized_result.append(serialized_line) return serialized_result if __name__ == "__main__": import sys if len(sys.argv) != 2: print(json.dumps({"error": "请传入图片路径参数"})) sys.exit(1) image_path = sys.argv[1] try: result = ocr_image(image_path) print(json.dumps(result)) except Exception as e: print(json.dumps({"error": str(e)})) sys.exit(1)
步骤2:在Python 3.11主程序中调用
通过subprocess模块调用Python 3.8解释器执行上述脚本,解析输出结果:
import subprocess import json def call_paddle_ocr(image_path): # 替换为你的Python 3.8解释器路径(如虚拟环境中的python.exe或/usr/bin/python3.8) python38_exec = "/path/to/your/python3.8" try: proc = subprocess.run( [python38_exec, "paddle_ocr_wrapper.py", image_path], capture_output=True, text=True, check=True ) return json.loads(proc.stdout) except subprocess.CalledProcessError as e: error_info = json.loads(e.stderr) if e.stderr else {"error": "调用失败"} return error_info # 调用示例 result = call_paddle_ocr("test_image.jpg") print(result)
方案二:长驻进程通信(适合频繁调用场景)
通过多进程队列实现Python 3.11主进程与Python 3.8 OCR进程的双向通信,避免重复启动进程的开销。
Python 3.11主程序代码
import multiprocessing as mp import json def ocr_worker(queue): # 此函数将在Python 3.8环境中执行 from paddleocr import PaddleOCR ocr = PaddleOCR(use_angle_cls=True, lang='ch') while True: task = queue.get() if task is None: # 接收退出信号 break image_path = task try: result = ocr.ocr(image_path, cls=True) # 序列化结果 serialized_result = [] for line in result: serialized_line = [[list(box) for box in line[0]], line[1][0], line[1][1]] serialized_result.append(serialized_line) queue.put({"result": serialized_result}) except Exception as e: queue.put({"error": str(e)}) def main(): # 指定Python 3.8解释器路径 python38_exec = "/path/to/your/python3.8" mp.set_executable(python38_exec) # 创建通信队列 task_queue = mp.Queue() worker = mp.Process(target=ocr_worker, args=(task_queue,)) worker.start() # 发送OCR任务 task_queue.put("test_image.jpg") result = task_queue.get() print(result) # 停止工作进程 task_queue.put(None) worker.join() if __name__ == "__main__": main()
注意事项
- 确保Python 3.8环境已正确安装PaddleOCR及其依赖,路径配置准确。
- 传递数据时优先使用JSON(避免pickle的版本兼容性问题),若需传递二进制图片数据,可改用临时文件或标准输入输出流。
- 方案一适合单次/低频次调用,方案二更适合高频次OCR请求场景。
内容的提问来源于stack exchange,提问作者azman
相关产品推荐
相关产品推荐

