python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python类库安装指定目录

Python实现类库安装指定目录的示例详解

作者:zhangfeng1133

这篇文章主要为大家详细介绍了Python实现类库安装指定目录的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

示例代码:

  TARGET_DIR="/gemine/code/python311"


wget https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.0.post1/flash_attn-2.7.0.post1+cu12torch2.4cxx11abiFALSE-cp311-cp311-linux_x86_64.whl

pip install flash_attn-2.6.3+cu118torch2.4cxx11abiFALSE-cp311-cp311-linux_x86_64.whl \
    --target=$TARGET_DIR \
    --no-deps \
    --no-build-isolation

TARGET_DIR="/gemine/code/python311" 添加到 Python 类库路径,有以下几种方法:

方法 1:临时添加(单次运行)

import sys
sys.path.insert(0, '/gemine/code/python311')

# 现在可以导入该目录下的包
import flash_attn

方法 2:永久添加(推荐)

2.1 添加到环境变量(~/.bashrc)

# 编辑 bashrc
echo 'export PYTHONPATH="/gemine/code/python311:$PYTHONPATH"' >> ~/.bashrc

# 立即生效
source ~/.bashrc

2.2 添加到 Python 启动文件

# 找到 Python 站点包目录
python -m site --user-site

# 创建 .pth 文件(假设输出是 /home/user/.local/lib/python3.11/site-packages)
echo "/gemine/code/python311" > /home/user/.local/lib/python3.11/site-packages/custom_path.pth

2.3 添加到 conda 环境(如果用 conda)

# 找到当前环境的 site-packages
python -c "import site; print(site.getsitepackages()[0])"

# 创建 .pth 文件
echo "/gemine/code/python311" > $(python -c "import site; print(site.getsitepackages()[0])")/custom_lib.pth

方法 3:Python 脚本中自动处理

import sys
import os

# 自动添加自定义库路径
TARGET_DIR = '/gemine/code/python311'

if TARGET_DIR not in sys.path:
    sys.path.insert(0, TARGET_DIR)
    print(f"已添加 {TARGET_DIR} 到 Python 路径")

# 验证
try:
    import flash_attn
    print(f"flash-attn 加载成功,版本: {flash_attn.__version__}")
except ImportError as e:
    print(f"加载失败: {e}")

方法 4:使用 .pth 文件(最干净)

# 一键添加(通用方法)
python << 'EOF'
import site
import os

target_dir = "/gemine/code/python311"
site_packages = site.getsitepackages()[0]
pth_file = os.path.join(site_packages, "custom_lib.pth")

# 写入 .pth 文件
with open(pth_file, 'w') as f:
    f.write(target_dir + '\n')

print(f"已创建: {pth_file}")
print(f"内容: {target_dir}")
EOF

验证是否生效

# 检查 Python 路径
python -c "import sys; print('/gemine/code/python311' in sys.path)"

# 检查能否导入 flash-attn
python -c "import flash_attn; print(flash_attn.__version__)"

推荐方案

场景推荐方法
临时测试方法 1(sys.path.insert)
个人长期使用方法 2.1(~/.bashrc)
项目独立配置方法 2.2(.pth 文件)
脚本自动化方法 3(代码中自动添加)

最推荐的是方法 2.2(.pth 文件),因为它:

需要我帮你写个一键配置脚本吗?

到此这篇关于Python实现类库安装指定目录的示例详解的文章就介绍到这了,更多相关Python类库安装指定目录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文