Skip to main content
 首页 » 编程设计

Python:运行时根据requirements.txt设置PYTHONPATH

2024年10月17日47telwanggs

我有一个带有命令行脚本的 Python 应用程序。我通过 setuptools“入口点”功能公开脚本。每当用户运行脚本时,我希望环境与包的 requirements.txt 一致。这意味着环境必须包含与 requirements.txt 中的版本说明符相匹配的每个依赖包的版本。

我知道这可以用 venv/virtualenv 来实现,方法是让我的用户创建一个虚拟环境,在其中安装 requirements.txt ,并在他们运行脚本时激活该虚拟环境。我不想将这种手动调用 virtualenv 的负担强加给用户。 Ruby 的 bundler 通过提供 bundler/setup 解决了这个问题——加载时,它修改 Ruby 的 $LOAD_PATH 以反射(reflect) 的内容Gemfile(类似于 requirements.txt)。因此它可以放在脚本的顶部以透明地控制运行时环境。 Python 有等价物吗?也就是说,一种在运行时根据 requirements.txt 设置环境而不会给用户带来额外复杂性的方法?

请您参考如下方法:

Does Python have an equivalent? That is, a way to set the environment at runtime according to requirements.txt without imposing additional complexity on the user?

是的,不止一个。

一个是pex

pex is a library for generating .pex (Python EXecutable) files which are executable Python environments in the spirit of virtualenvs.

另一个是Platter :

Platter is a tool for Python that simplifies deployments on Unix servers. It’s a thin wrapper around pip, virtualenv and wheel and aids in creating packages that can install without compiling or downloading on servers.