본문 바로가기

개발이야기/Python

Python 프로젝트 구성 끝판왕 Pyenv + Poetry

728x90

Python으로 많은 것들을 할 수 있다.

단순한 프로그램 부터, 웹, ML 등 많은 프로젝트들을 Python을 사용해 만들어낼 수 있다.

보통 프로젝트를 시작하는 경우는 내가 처음 프로젝트를 시작하거나, 아니면 다른 사람이 먼저 시작한 프로젝트에 참여하거나..

두가지 경우가 있을거같다.

 

Python은 기본적으로 아주 느슨한 의존성 관리툴을 탑재하고 있다.

(pip, requirements.txt..)

Python프로젝트를 다른 사람과 같이 진행하다 보면 "어? 내 PC에서는 동작하는데?" 를 시전하는 경우가 적지 않다.

패키지 의존성 문제나, 서로 다른 Python 버전을 사용하는 경우 이런 Case가 발생한다.

 

Pyenv와 Poetry를 같이 사용하면 위와 같은 문제를 대부분 해결 할 수 있다.


Pyenv

Pyenv는 하나의 PC에 여러 Python 버전을 설치하고 관리하는 툴이다.

프로젝트마다 Python 버전을 설정할 수 있다.

 

만약 새로운 프로젝트를 설정하고 python 3.11.3 버전을 해당 프로젝트에서만 사용하려면 아래처럼 pyenv를 통해 설정이 가능하다.

$ cd test_project
$ pyenv install 3.11.3
...
$ pyenv local 3.11.3
$ ls -a
.python-version
$ cat .python-versoin
3.11.3

자세한 내용은 아래 Post를 확인 바란다.

2023.01.26 - [개발이야기/Python] - Pyenv 설치와 사용법 - Python 버전 관리 도구

 

Poetry

 Poetry는 Python 의존성 관리 도구 이다.

컨셉은 node.js의 npm 과 비슷한다.

 

Poetry에서 제공하는 Script를 사용해 쉽게 설치할 수 있다. (Mac, Linux 기준)

curl -sSL https://install.python-poetry.org | python3 -

pip로도 설치가 가능하다.

pip install poetry

 

아래와 같이 새로운 Python 프로젝트를 생성할 수 있다.

$ poetry new test_project
$ cd test_project
$ tree -a .
.
├── README.md
├── pyproject.toml
├── tests
│   └── __init__.py
└── test_project
    └── __init__.py

3 directories, 4 files

또는 아래와 같이 init으로도 새로운 프로젝트를 만들 수 있다.

이 경우 README.md, tests, project 폴더 등은 생성이 되지 않아 직접 생성해줘야 한다.

$ mkdir test_project
$ cd test_project
$ poetry init   

This command will guide you through creating your pyproject.toml config.

Package name [test_project]:  
Version [0.1.0]:  
Description []:  
Author [김태주 <iam@taeju.kim>, n to skip]:  
License []:  
Compatible Python versions [^3.11]:  

Would you like to define your main dependencies interactively? (yes/no) [yes] 

...

Package to add or search for (leave blank to skip): django
Found 20 packages matching django
Showing the first 10 matches

Enter package # to add, or the complete package name if it is not listed []:
 [ 0] Django
 [ 1] django-503
 [ 2] django-filebrowser-django13
 [ 3] django-tracking-analyzer-django2
 [ 4] django-jchart-django3-uvm
 [ 5] django-totalsum-admin-django3
 [ 6] django-debug-toolbar-django13
 [ 7] django-suit-redactor-django2
 [ 8] django-django_csv_exports
 [ 9] django-directapps
 [ 10] 
 > 0
Enter the version constraint to require (or leave blank to use the latest version): 
Using version ^4.2.1 for Django

Add a package (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 = "test-project"
version = "0.1.0"
description = ""
authors = ["김태주 <taeju.kim@woowahan.com>"]
readme = "README.md"
packages = [{include = "test_project"}]

[tool.poetry.dependencies]
python = "^3.11"
Django = "^4.2.1"


[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"


Do you confirm generation? (yes/no) [yes]

 

하지만, 위와 같이 Python 프로젝트를 생성하면 필요한 패키지들을 바로 추가할 수 있다.

 

$ poetry install
Creating virtualenv test-project-sYnn_uMx-py3.11 in /Users/taeju.kim/Library/Caches/pypoetry/virtualenvs
Updating dependencies
Resolving dependencies... (0.2s)

Package operations: 3 installs, 0 updates, 0 removals

  • Installing asgiref (3.7.2)
  • Installing sqlparse (0.4.4)
  • Installing django (4.2.1)

Writing lock file

위와 같이 수행하면 새로운 Python 가상환경이 생성되고 해당 가상환경에 위에서 설정했던 Python 패키지가 설치 된다.

설치가 완료되면 poetry.lock 파일이 생성된다.

 

새로운 패키지를 추가할때는 add 명령을 사용한다.

$ poetry add pydantic            
Using version ^1.10.8 for pydantic

Updating dependencies
Resolving dependencies... (0.1s)

Package operations: 2 installs, 0 updates, 0 removals

  • Installing typing-extensions (4.6.2)
  • Installing pydantic (1.10.8)

Writing lock file

새로운 환경에서 기존 프로젝트를 사용하려면 소스코드를 모두 내려받은 후 install 명령을 수행하기만 하면된다.

$ poetry install

poetry 는 자동으로 Python 가상환경을 생성한다.

프로젝트별 가상환경을 사용하기 위해서는 아래처럼 프로젝트 폴더에 진입 후 shell 명령을 사용하면된다.

$ poetry shell 
Spawning shell within /Users/taeju.kim/Library/Caches/pypoetry/virtualenvs/test-project-XpO57-p--py3.11
$ which python
/Users/taeju.kim/Library/Caches/pypoetry/virtualenvs/test-project-XpO57-p--py3.11/bin/python

만약 pytest를 사용한다면 프로젝트 root에 pytest.ini 파일을 생성해야 하는데, 

poetry를 사용한다면 pytest.ini 파일의 설정은 pyproject.toml 파일안에 작성할 수 있다.

# pyproject.toml
[tool.pytest.ini_options]
minversion = "6.0"
addopts = "-ra -q"
testpaths = [
    "tests",
    "integration",
]

이처럼 Pyenv 와 Poetry 를 조합해 사용하게 되면 프로젝트별 Python 버전과 의존성 관리를 쉽게 할 수 있다.

Poetry를 npm 과 비슷한 컨셉으로 강력한 편의성을 제공하여 프로젝트를 효율적으로 관리할 수 있게 도와 준다.

이 글에서 설명하지는 않았지만 Poetry는 프로젝트의 실행 및 배포 기능도 담고 있다.

의존성 관리, 가상환경 생성 및 실행, 실행 및 배포 까지 모두 Poetry를 통해 쉽게 처리할 수 있다.

 

지금 바로 Poetry를 사용해보자.