> For the complete documentation index, see [llms.txt](https://lswkim322.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lswkim322.gitbook.io/til/til-ml/untitled-2/poetry-dependency.md).

# Poetry로 dependency 관리

## 1. Poetry란?

파이썬 의존성 관리 툴 (Maven, Gradle 같은거)

{% embed url="<https://python-poetry.org/docs>" %}

## 2. Install & Setting

### 2.1. Install

#### 리눅스에서 설치하기

```
apt-get install -y curl
```

```
curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python
```

```
source $HOME/.poetry/env
```

#### pip 로 설치하기

```
pip install --user poetry
```

### 2.2. Setting

#### Project 생성

```
poetry new my-project
```

```
my-project tree
.
├── README.rst
├── my_project
│   └── __init__.py
├── pyproject.toml
└── tests
    ├── __init__.py
    └── test_my_project.py
```

pyproject.toml 이 의존성을 관리하는 파일이다. 스프링을 할 때 maven의 pom.xml 이나 gradle의 build.gradle 파일을 생각하면 될 것 같다.

```python
[tool.poetry]
name = "my-project"
version = "0.1.0"
description = ""
authors = ["andy.sg"]

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

[tool.poetry.dev-dependencies]
pytest = "^5.2"

[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
```

추가를 하고 싶으면 `add`

```
poetry add django
```

`poetry.lock` 파일이 내가 작성하고 있는 프로젝트와 동일한 의존성을 가지도록 할 수 있는 파일이다.

파일 내에 버전 범위를 표현하는 기호는 공식 문서를 참고하자.

<https://python-poetry.org/docs/dependency-specification/>

## 3. 명령어

#### (이미 너무 정리가 잘되어 있어서 내용을 그대로 퍼왔습니다. 출처는 하단)

#### new

`new` 명령어로 새로운 프로젝트를 만들 수 있습니다.

```
poetry new my-site
```

위 명령어를 실행하면 아래와 같은 기본 디렉토리 구성을 만들어줍니다.

```
my-site
├── pyproject.toml
├── README.rst
├── src
│   └── my_site
│       └── __init__.py
└── tests
    ├── __init__.py
    └── test_my_site.py
```

#### init

`init` 커맨드는 `pyproject.toml` 파일을 인터렉티브 하게 만들 수 있도록 도와줍니다.

```
poetry init
```

#### install

`install` 커맨드는 현재 프로젝트의 `pyproject.toml` 파일을 읽어서 의존성 패키지를 설치해줍니다. `poetry.lock` 이 없으면 만들어주고 있으면 해당파일을 사용하게됩니다.

```
# 의존성 설치
poetry install

# 개발환경의 의존성은 빼고 설치
poetry install --no-dev

# -E 또는 --extras 로 추가 의존성을 설정가능
poetry install --extras "mysql redis"
poerty install -E mysql -E redis
```

#### update

의존성 패키지의 버전을 업데이트하고 `poetry.lock` 파일을 업데이트 합니다.

```
# 패키지 업데이트
poerty update

# 하나씩 지정해서 업데이트도 가능
poetry update requests toml

# 업데이트는 하지 않고 poetry.lock 만 업데이트
poerty update --lock
```

#### add

패키지설정을 pyproject.toml 에 추가합니다.

```
poetry add django

# 개발환경에서 필요한 패키지 설치
poetry add pytest factory-boy --dev

# 버전을 지정가능
poetry add django@^3.0.0
poetry add "django=3.0.0"

# 최신버전을 설치
poetry add django@latest

# 깃 저장소에 있는 패키지 설치
poetry add git+https://github.com/django/django.git

# 깃 저장소의 패키지에서 브랜치를 지정
poetry add git+https://github.com/django/django.git#stable/2.2.x

# 로컬에 디렉토리의 파일로 설치하기
poetry add ./my-package/
poetry add ./my-package/dist/my-package-0.1.0.tar.gz
poetry add ./my-package/dist/my-package-0.1.0.whl
```

#### remove

패키지 삭제

```
poetry remove flask

# 개발환경 패키지 삭제
poetry remove pytest
```

#### show

```
# 설치된 모든 패키지를 보여준다.
poetry show

# 개발환경용 제외하고 보여준다.
poetry show --no-dev

# 특정패키지를 지정하면 상세내용을 보여줍니다.
poetry show django

# 최신 버전을 보여준다.
poetry show --latest (-l)

# 업데이트를 해야하는 패키지들을 보여준다.
poetry show --outdate (-o)

# 의존성 트리를 보여준다.
poetry show --tree
```

#### build

위에도 적었지만 소스를 배포가능한 형태로(tarball, wheel)빌드합니다.

```
poetry build
```

#### publish

아래 명령어로 PyPI에 배포할 수 있습니다.

```bash
poerty publish
```

배포를 하려면 PyPI 계정이 필요합니다. 계정이 없다면 [여기를 클릭](https://pypi.org/account/register/) 하시고 하나 만드셔도 좋습니다. 프로젝트명이 겹치면 배포를 할 수 없으니, 자신만의 독특한 프로젝트 명을 정해서 배포를 해보도록 합시다.

#### config

`config` 커맨드로 poetry 관련 설정을 변경할 수 있습니다.

```
# 설정보기
poetry config --list


# 설정법
poetry config [options] [setting-key] [setting-value1] ... [setting-valueN]
```

#### run

프로젝트의 virtualenv 에 커맨드를 전달하여 실행하게 됩니다.

```
poetry run python -V
```

#### check

`pyproject.toml` 의 유효함을 체크하는 명령어입니다.

#### search

패키지를 찾기위한 커맨드입니다. 예를들어 beautifulsoup 의 패키지명의 철자가 기억이 안나고 beautiful 만 기억나면 아래와 같이 할 수 있습니다 .

```
$ poetry search beautiful | grep soup

---------------------------------
# output
beautifulsoup (3.2.2)
beautifulsoup4 (4.9.1)
```

#### lock

`pyproject.toml` 에 설정된 의존성들에 대한 lock 파일을 생성합니다. (설치X)

#### export

export 명령어는 lock 파일을 사용해서 다른 의존성 포맷으로 변경할 수 있습니다.

```
poetry export -f requirements.txt > requirements.txt
```

### 가상 환경 관리하기

poetry 로 가상환경(virtualenv)을 관리 할 수 있습니다.

일반적으로 아래와 같이 사용합니다.

```bash
$ poetry env use {파이썬경로}
```

만약에 python3 이 패스에 잡혀 있는 상황이라면 모든 경로를 적어주지 않아도 됩니다.

```bash
$ poetry env use python3
```

#### 가상환경 정보보기

`poetry env info` 커맨드로 환경 정보를 확인할 수 있습니다.

저의 경우는 아래와 같이 출력되었습니다.

```bash
Virtualenv
Python:         3.8.1
Implementation: CPython
Path:           /Users/gyus/Library/Caches/pypoetry/virtualenvs/my-project-0CozYJQl-py3.8
Valid:          True

System
Platform: darwin
OS:       posix
Python:   /Users/gyus/.pyenv/versions/3.8.1
```

단순하게 가상환경의 path만 알고 싶은 경우라면 `--path` 옵션을 주면 됩니다.

```bash
$ poetry env info --path
```

#### 가상환경 리스트 보기

만들어진 가상환경의 리스트는 아래의 명령어로 확인 가능합니다.

```bash
$ poetry env list
```

#### 가상환경 삭제하기

삭제는 아래의 명령어로 가능합니다.

```bash
$ poetry env remove {python경로}
```

## Reference

{% embed url="<https://blog.gyus.me/2020/introduce-poetry>" %}
