Skip to main content
 首页 » 编程设计

python之将第三方包目录添加到 Python 路径开头的最干净的方法是什么

2025年05月04日6Free-Thinker

我的上下文是 appengine_config.py,但这确实是一个一般的 Python 问题。

鉴于我们已经克隆了一个应用程序的 repo,其中有一个空目录 lib,并且我们使用命令 用包填充了 lib >pip install -r requirements.txt --target lib,然后:

dirname ='lib' 
dirpath = os.path.join(os.path.dirname(__file__), dirname) 

为了导入目的,我们可以通过以下方式将这样的文件系统路径添加到 Python 路径的开头(我们使用索引 1,因为第一个位置应该保留为“.”,即当前目录):

sys.path.insert(1, dirpath) 

但是,如果该目录中的任何包是命名空间包,那将不起作用。

为了支持命名空间包,我们可以改用:

site.addsitedir(dirpath) 

但这会将新目录附加到路径的末尾,我们不希望这样,以防我们需要用较新的版本覆盖平台提供的包(例如 WebOb)。

到目前为止,我的解决方案是我非常想简化的这段代码:

sys.path, remainder = sys.path[:1], sys.path[1:] 
site.addsitedir(dirpath) 
sys.path.extend(remainder) 

是否有更简洁或更 Pythonic 的方法来完成此任务?

请您参考如下方法:

对于这个答案,我假设您知道如何使用 setuptools 和 setup.py。

假设您想使用标准的 setuptools 工作流程进行开发,我建议您使用 appengine_config.py 中的这段代码:

import os 
import sys 
 
if os.environ.get('CURRENT_VERSION_ID') == 'testbed-version': 
    # If we are unittesting, fake the non-existence of appengine_config. 
    # The error message of the import error is handled by gae and must 
    # exactly match the proper string. 
    raise ImportError('No module named appengine_config') 
 
 
# Imports are done relative because Google app engine prohibits 
# absolute imports. 
lib_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'libs') 
# Add every library to sys.path. 
if os.path.isdir(lib_dir): 
    for lib in os.listdir(lib_dir): 
        if lib.endswith('.egg'): 
            lib = os.path.join(lib_dir, lib) 
            # Insert to override default libraries such as webob 1.1.1. 
            sys.path.insert(0, lib) 

setup.cfg中的这段代码:

[develop] 
install-dir = libs 
always-copy = true 

如果您键入 python setup.py develop,库将作为 egg 下载到 libs 目录中。 appengine_config 将它们插入您的路径。

我们在工作中使用它来包含 webob==1.3.1 和内部包,它们都使用我们公司的命名空间进行命名。