You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MacOS下Blender Python脚本导入指定相对文件夹模块失败求助

问题原因与解决方案

问题根源

你将_scripts目录添加到了sys.path,但colorthief.py实际位于_scripts/color-thief-py-master子目录中。Python查找模块时,只会遍历sys.path中直接列出的目录,不会自动递归子文件夹,因此无法找到目标模块。

跨平台解决方案

推荐采用**遍历_scripts下所有子目录并添加到sys.path**的方式,一次性解决所有模块仓库的导入问题,同时兼容Windows、MacOS、Linux等平台。

代码实现(os.path版本)

import os
import sys
import bpy
from os.path import dirname as up

# 先检查.blend文件是否已保存(未保存时bpy.data.filepath为空)
if not bpy.data.filepath:
    raise Exception("请先保存当前.blend文件,否则无法获取相对路径")

# 获取_scripts文件夹的绝对路径
packages_root = os.path.join(up(bpy.data.filepath), "_scripts")

# 遍历_scripts下的所有子目录,添加到sys.path头部
for item in os.listdir(packages_root):
    item_path = os.path.join(packages_root, item)
    if os.path.isdir(item_path) and item_path not in sys.path:
        sys.path.insert(0, item_path)

# 现在可以正常导入模块
from colorthief import ColorThief

代码实现(pathlib版本,更简洁)

import sys
import bpy
from pathlib import Path

# 检查.blend文件是否已保存
if not bpy.data.filepath:
    raise Exception("请先保存当前.blend文件,否则无法获取相对路径")

# 获取_scripts文件夹路径
blend_dir = Path(bpy.data.filepath).parent
packages_root = blend_dir / "_scripts"

# 遍历子目录并添加到sys.path
for item in packages_root.iterdir():
    if item.is_dir() and str(item) not in sys.path:
        sys.path.insert(0, str(item))

# 正常导入模块
from colorthief import ColorThief

其他可选方案

如果仅需导入特定模块仓库,可直接将该仓库的路径添加到sys.path:

import os
import sys
import bpy
from os.path import dirname as up

if not bpy.data.filepath:
    raise Exception("请先保存当前.blend文件,否则无法获取相对路径")

packages_root = os.path.join(up(bpy.data.filepath), "_scripts")
# 单独添加color-thief-py-master的路径
color_thief_path = os.path.join(packages_root, "color-thief-py-master")
if color_thief_path not in sys.path:
    sys.path.insert(0, color_thief_path)

from colorthief import ColorThief

内容的提问来源于stack exchange,提问作者ReallyRosie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 16:22:34