如何使用Python Poetry以独立的方式将软件包安装到虚拟环境中?

3

我最近刚刚迁移到了 poetry 作为我的依赖管理工具,如果我的问题与 poetry 无关,请见谅。

最终目标

我的最终目标是创建一个包含 virtualenv 和我的软件及其所有依赖项RPM 包。这个 RPM 包将在安装的系统中提供我的软件的 隔离环境

重现问题

在使用 virtualenv 中的 poetry install 时,我遇到了一个问题。只要删除了我的软件的 源代码目录,我的 CLI 就会停止工作。

重现

我创建了一个简单的存储库来重现这个问题: https://github.com/riton/python-poetry-venv

这是我使用 poetry 的命令:

#!/bin/bash -ex

VENV_DIR="/venv"
SRC_DIR="/src"
ALT_SRC_DIR="/src2"
USER_CACHE_DIR="~/.cache"

# Copy directory (cause we're mounting it read-only in the container)
# and we want to remove the source directory later on
cp -r $SRC_DIR $ALT_SRC_DIR

# We'll remove this directory to test if the soft is still working
# without the source dir
cd $ALT_SRC_DIR

[...]

python3.8 -m venv "$VENV_DIR"

source $VENV_DIR/bin/activate

[...]

poetry install --no-dev -v

[...]

# Our software will be called without an activated virtualenv
# so 'deactivate' the current one
deactivate

cd /

echo "Try after install"

# Start the "CLI" after installation
$VENV_DIR/bin/python-poetry-venv

echo "Removing source directory and trying again"
rm -rf $ALT_SRC_DIR

$VENV_DIR/bin/python-poetry-venv

echo "Removing user cache dir and trying again"
rm -rf $USER_CACHE_DIR

$VENV_DIR/bin/python-poetry-venv

上面的脚本会出现以下错误:
[...]
Try after install
+ /venv/bin/python-poetry-venv
THIS IS THE MAIN
+ echo 'Removing source directory and trying again'
Removing source directory and trying again
+ rm -rf /src2
+ /venv/bin/python-poetry-venv
Traceback (most recent call last):
  File "/venv/bin/python-poetry-venv", line 2, in <module>
    from python_poetry_venv.cli import main
ModuleNotFoundError: No module named 'python_poetry_venv'
make: *** [Makefile:2: test-with-poetry-install] Error 1

完整脚本源代码链接

一旦删除了源目录,CLI就不再起作用。

尝试使用pip install

我尝试将poetry install替换为poetry build && pip install dist/*.whl此脚本版本的链接

使用pip install安装.whl文件的版本,我成功地创建了我的应用程序的独立部署。这适合RPM打包,并可在任何地方部署。

软件版本

+ python3.8 -V        
Python 3.8.13
          
+ poetry --version   
Poetry version 1.1.13

总结

我不禁想到我可能在这里误用了poetry,因此非常感谢任何帮助。

提前致谢。

祝好


你不需要激活虚拟环境,poetry会为你处理。 - Sergio Lema
1个回答

6

我来晚了,但是我想提出一种实现这个目标的方法。 虽然poetry可以很好地管理项目的主要和开发依赖项并锁定它们的版本,但在部署时我不会依赖它。下面是解决问题的方法:

# export your dependencies in the requirements.txt format using poetry
poetry export --without-hashes -f requirements.txt -o requirements.txt

# create your venv like you did on your example (you may want to upgrade pip/wheel/setuptools first)
python3 -m venv venv && . venv/bin/activate

# then install the dependencies
pip install --no-cache-dir -r requirements.txt

# then you install your own project
pip install .

就是这样,你所需的一切都将包含在venv文件夹中


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接