DEV Community

drake
drake

Posted on

Python 包管理工具Poetry使用

  • 1、安装
curl -sSL https://install.python-poetry.org | python -
Enter fullscreen mode Exit fullscreen mode
  • 2、包管理的方式

poetry默认是与项目强绑定的,这点和pip就不同;

poetry默认安装的包都是默认安装在虚拟环境的,比如:
'. /Users/drake/Library/Caches/pypoetry/virtualenvs/spider-LtrDnC5E-py3.12/bin/activate'

'. /Users/drake/Library/Caches/pypoetry/virtualenvs/bgspider-0XALnWtL-py3.12/bin/activate'

  • 3、包管理命令(1)
poetry add requests
Enter fullscreen mode Exit fullscreen mode
  • 4、因包管理命令而生成的配置文件

pyproject.toml 这是最核心的文件,这里面列了依赖清单;
poetry add 会先检查是否存在该文件,并且根据文件内的制定版本安装
如果不存在该文件,会自动的新建的

poetry.lock 这个文件是根据pyproject.toml自动生成的;
当缺少peotry.lock,或者peotry.lock没有被更新的时候(这种情况一般不存在),可以通过poetry lock 来新建和更新该文件。

  • 5、包管理命令(2)
poetry install --no-root
Enter fullscreen mode Exit fullscreen mode

一定要加 --no-root 否则poetry install 会把项目本身的整个目录作为一个包,安装到虚拟环境中去,这显然不是我们想要的

该命令是根据配置文件安装依赖的,前提是有配置文件存在;
读取配置文件的顺序是poetry.lock ,如果该文件不存在,则会读取pyproject.toml ,然后再自动生成poetry.lock

  • 6、调用虚拟环境,进行项目开发调试

1、终端中,直接在项目根目录下执行 poetry shell ,将会进入虚拟环境的终端;
在该虚拟环境中pip list 或者 poetry show 你将能看到你安装的依赖,否则将什么也看不到
2、执行poetry shell的时候,会返回虚拟环境所在的具体路径,比如:/Users/drake/Library/Caches/pypoetry/virtualenvs/bgspider-0XALnWtL-py3.12

记住该路径,然后在pycharm 中的设置里,配置 Python interpreter 新增interpreter, 根据上面的路径配置进去

  • 7、在别的项目中复用配置文件

复制pyproject.toml文件到新项目的根目录,但需要将[tool.poetry] 分类下的name属性改为新项目的名字,如果下面的test改成你自己新项目的名称
[tool.poetry]
name = "test"

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up