본문 바로가기
Language/Python

Poetry를 사용해서 파이썬 패키지를 관리해보자

by 홍띠 2024. 8. 4.

Poetry란

파이썬에서 패키지 배포와 의존성 관리를 쉽게 해주는 도구이다. 프로젝트에 따라 라이브러리를 선언하고 설치/업데이트/관리할 수 있다. 의존성 관리를 위한 pyenv, venv같은 가상환경의 역할을 대체 할 수 있으며, 더해서 패키지 배포까지 쉽게 가능하게 해준다.

pyproject.toml 파일을 활용해서 의존성을 관리하여, 기존의 setup.py, requirements.txt, setup.cfg, MANIFEST.in , Pipfile 과 같은 파일들을 하나의 pyproject.toml 로 대체 할 수 있다.

Poetry 사용을 위해서는 Python 3.8 버전 이상이 필요하다.

Poetry 설치

official installer로 설치 - https://python-poetry.org/docs/#installing-with-the-official-installer

  • Linux, macOS, Windows (WSL) 에서 설치
curl -sSL https://install.python-poetry.org | python3 -
  • Windows (Powershell) 에서 설치
(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py -
  • 업데이트
poetry self update
  • 삭제
curl -sSL https://install.python-poetry.org | python3 - --uninstall
curl -sSL https://install.python-poetry.org | POETRY_UNINSTALL=1 python3 -
  • 자동완성 설정 - Auto-loaded (recommended)
poetry completions bash >> ~/.bash_completion

Poetry 사용하기

  • 신규 프로젝트 생성 - poetry를 이용
poetry new demo-project
  • demo-project 이름의 디렉토리가 생성되며 아래와 같은 기본 파일들이 생성된다.
.
├── README.md
├── demo_project
│   └── __init__.py
├── pyproject.toml
└── tests
    └── __init__.py
  • 기존 프로젝트에서 poetry 초기화
    • 프로젝트 디렉토리 접근 후 poetry 초기화
      # 프로젝트 디렉토리에 접근해서 init 명령어를 실행한다.
      cd pre-existing-project
      poetry init
      
      # 아래 내용이 출력되면 상황에 맞게 설정값을 입력하고 엔터를 눌러서 진행한다.
      
      This command will guide you through creating your pyproject.toml config.
      
      Package name [pre-existing-project]:  
      Version [0.1.0]:  
      Description []:  
      Author [test <test@test.io>, n to skip]:  
      License []:  
      Compatible Python versions [^3.11]:  3.8
      
      Would you like to define your main dependencies interactively? (yes/no) [yes] 
      You can specify a package in the following forms:
        - A single name (requests): this will search for matches on PyPI
        - A name and a constraint (requests@^2.23.0)
        - A git url (git+https://github.com/python-poetry/poetry.git)
        - A git url with a revision (git+https://github.com/python-poetry/poetry.git#develop)
        - A file path (../my-package/my-package.whl)
        - A directory (../my-package/)
        - A url (<https://example.com/packages/my-package-0.1.0.tar.gz>)
      
      Package to add or search for (leave blank to skip): 
      
      Would you like to define your development dependencies interactively? (yes/no) [yes] 
      Package to add or search for (leave blank to skip): 
      
      Generated file
      
      [tool.poetry]
      name = "pre-existing-project"
      version = "0.1.0"
      description = ""
      authors = ["test <test@test.io>"]
      readme = "README.md"
      
      [tool.poetry.dependencies]
      python = "3.8"
      
      [build-system]
      requires = ["poetry-core"]
      build-backend = "poetry.core.masonry.api"
      </test@test.io></test@test.io>

프로젝트를 생성하거나 초기화 하면pyproject.toml 이 자동으로 생성되는데, 이 파일은 poetry에서 프로젝트 설정과 의존성을 관리하는 중요한 파일이다.

[tool.poetry]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = ["Sébastien Eustace <sebastien@eustace.io>"]
readme = "README.md"
packages = [{include = "poetry_demo"}]

[tool.poetry.dependencies]
python = "^3.8"


[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
    • Poetry는 기본적으로 tool.poetry.name 에 표기된 이름과 동일한 이름의 패키지가 프로젝트 루트디렉토리에 있다고 가정한다, 따라서 예외의 경우에는 tool.poetry.packages 값을 설정해서 패키지와 위치를 지정한다.
    • tool.poetry.dependencies 에서 파이썬과 라이브러리들의 버전을 지정하여 의존성을 관리한다.
  •  

의존성 추가

패키지 추가 - add 명령어를 실행하면 pyproject.toml 에 해당 라이브러리들이 추가된다.

  • 라이브러리 추가
poetry add pendulum
poetry add django@^4.0.0

# Django = "^4.0.0"

 

  • 개발 dependencies로 패키지 추가
poetry add --dev pendulum
  • 패키지 삭제
poetry remove pendulum

 

가상환경 활성화

  • poetry 가상환경 활성화
poetry shell
  • pyenv를 활용해서 파이썬 버전 자유롭게 설정
pyenv install 3.9.8
pyenv local 3.9.8  # Activate Python 3.9 for the current project
eval "$(pyenv init -)"
poetry install