通过Popen子进程调用Python脚本时库导入失败求助
解决方案
1. 调整sys.path添加顺序(核心修复)
你的问题根源之一是sys.path的添加时机太晚:from detection_Inference import *会立即触发detection_Inference.py的执行,而该脚本里导入notebook_utils时,你还没把utils目录加入sys.path。必须把路径添加代码放在所有导入操作之前:
import sys # 优先添加绝对路径,避免工作目录变化导致相对路径失效 sys.path.append(r"C:\basic_detection\utils") # 可选保留相对路径,但绝对路径更可靠 sys.path.append("./utils") import argparse from detection_Inference import * from notebook_utils import segmentation_map_to_image, to_rgb parser = argparse.ArgumentParser()
2. 固定Popen子进程的工作目录
Popen默认继承父进程的工作目录,如果父进程不在C:\basic_detection,相对路径./utils会指向错误位置。调用时指定cwd参数强制子进程在目标目录运行:
from subprocess import Popen, PIPE # 假设command_arg_list是["python", "creatorop.py"]这类命令 process = Popen( command_arg_list, shell=True, stdout=PIPE, stderr=PIPE, cwd=r"C:\basic_detection" # 明确指定脚本所在目录为工作目录 )
3. 备选方案:在detection_Inference.py中直接补全路径
如果不想修改creatorop.py的导入顺序,也可以在detection_Inference.py开头添加路径:
import sys sys.path.append(r"C:\basic_detection\utils") from notebook_utils import segmentation_map_to_image, to_rgb # 剩余代码...
调试技巧:验证路径是否生效
可以在导入前打印sys.path,确认utils目录是否被正确加入:
import sys print("当前sys.path:", sys.path) sys.path.append(r"C:\basic_detection\utils") print("更新后sys.path:", sys.path)
内容的提问来源于stack exchange,提问作者PCG
相关产品推荐
相关产品推荐

