WindowsマシンでPython環境構築をpoetry + pyenvで再度やってみた

2024.04.15

こんちには。

データアナリティクス事業本部 機械学習チームの中村(nokomoro3)です。

2024年4月になった(?)ので、本記事ではWindowsマシンでPython環境構築をpoetry + pyenvを使ってやってみたいと思います。

(実際はマイPCが調子悪くなったので入れ直そうと思ったら、前と手順が変わってたので備忘録です…)

はじめに

poetryはpipxを使って入れるようアナウンスされており、pipxはscoopを使って入れるようにアナウンスされています。

ですので、Scoopから順にPython、pipx、poetryと入れていきます。

Scoopをいれる

ScoopはWindows向けのコマンドラインインストーラです。

以下にセットアップ手順が記載されていますのでその通りに進めます。

PowerShellで以下を実行します。

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Invoke-RestMethod -Uri https://get.scoop.sh | Invoke-Expression

# Initializing...
# Downloading...
# Creating shim...
# Adding ~\scoop\shims to your path.
# Scoop was installed successfully!
# Type 'scoop help' for instructions.

バージョンを確認しておきます。

scoop --version

# Current Scoop version:
# v0.3.1 - Released at 2022-11-15
#
# 'main' bucket:
# 6e2463abb (HEAD -> master, origin/master, origin/HEAD) supabase: Update to version 1.157.1

Pythonを入れる

pipxを入れる際に「'pipx' suggests installing 'python'.」とメッセージが出たので、先にPythonを入れておきます。

なお後でpyenvを入れますが、こちらはシステム側のPythonをインストールする感じです。

scoopを使ってPythonを入れます。

scoop install python

# Installing 'dark' (3.14) [64bit] from main bucket
# dark-3.14.zip (5.0 MB) [======================================================================================] 100%
# Checking hash of dark-3.14.zip ... ok.
# Extracting dark-3.14.zip ... done.
# Linking ~\scoop\apps\dark\current => ~\scoop\apps\dark\3.14
# Creating shim for 'dark'.
# 'dark' (3.14) was installed successfully!
# Installing 'python' (3.12.2) [64bit] from main bucket
# python-3.12.2-amd64.exe (25.4 MB) [===========================================================================] 100%
# Checking hash of python-3.12.2-amd64.exe ... ok.
# Running pre_install script...
# Running installer script...
# Linking ~\scoop\apps\python\current => ~\scoop\apps\python\3.12.2
# Creating shim for 'python3'.
# Creating shim for 'idle'.
# Creating shim for 'idle3'.
# Persisting Scripts
# Persisting Lib\site-packages
# Running post_install script...
#
# 'python' (3.12.2) was installed successfully!
# Notes
# -----
# Allow applications and third-party installers to find python by running:
# "C:\Users\{ご自身のユーザ名}\scoop\apps\python\current\install-pep-514.reg"

pipxを入れる

次にpipxを入れます。公式ドキュメントは以下のように説明されています。

pipx is a tool to help you install and run end-user applications written in Python. It's roughly similar to macOS's brew, JavaScript's npx, and Linux's apt. It's closely related to pip. In fact, it uses pip, but is focused on installing and managing Python packages that can be run from the command line directly as applications.

pipはPythonのパッケージをインストールするツールですが、pipxはCLIから直接呼び出せるPythonアプリケーションをインストールする用途という感じのようです。

インストールは以下に従って進めます。

まずはScoopを使ってインストールをします。

scoop install pipx

# Installing 'pipx' (1.5.0) [64bit] from main bucket
# pipx.pyz (311.8 KB) [=========================================================================================] 100%
# Checking hash of pipx.pyz ... ok.
# Running pre_install script...
# Linking ~\scoop\apps\pipx\current => ~\scoop\apps\pipx\1.5.0
# Creating shim for 'pipx'.
# 'pipx' (1.5.0) was installed successfully!

その後、PATHを追加するコマンドを実行します。

pipx ensurepath

# Success! Added C:\Users\{ご自身のユーザ名}\.local\bin to the PATH environment variable.
#
# Consider adding shell completions for pipx. Run 'pipx completions' for instructions.
#
# You will need to open a new terminal or re-login for the PATH changes to take effect.
#
# Otherwise pipx is ready to go! ✨ 🌟 ✨

後述のように、pipxを使ってインストールされるアプリケーションはC:\Users\{ご自身のユーザ名}\.local\binに格納されるようです。

poetryを入れる

poetryを入れていきます。インストールは以下に従って進めます。

pipxを使ってpoetryを入れていきます。

pipx install poetry

#   installed package poetry 1.8.2, installed using Python 3.12.2
#   These apps are now globally available
#     - poetry.exe
# done! ✨ 🌟 ✨
poetry --version

# Poetry (version 1.8.2)

以上の設定で、Git for Bash等でもpoetryが実行できるようになっているはずです。VSCodeからGit for Bashを起動している場合は、VSCodeごと再起動してみてください。

poetryの場所は以下となっているかと思います。

which poetry

# /c/users/nakamura.shogo/.local/bin/poetry

pipxを使ってインストールされるアプリケーションはC:\Users\{ご自身のユーザ名}\.local\binに格納されるようです。

pyenvも入れる

pyenvは従来通り、pyenv-winをインストールする必要があります。

Invoke-WebRequest -UseBasicParsing -Uri "https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/pyenv-win/install-pyenv-win.ps1" -OutFile "./install-pyenv-win.ps1"; &"./install-pyenv-win.ps1"

#     ディレクトリ: C:\Users\{ご自身のユーザ名}
#
#
# Mode                 LastWriteTime         Length Name
# ----                 -------------         ------ ----
# d-----        2024/04/15     16:21                .pyenv
# pyenv-win is successfully installed. You may need to close and reopen your terminal before using it.

インストールの確認をします。

pyenv --version

# pyenv 3.1.1

再インストールしたい場合はC:\Users\{ご自身のユーザ名}\.pyenvを削除してからやり直せばOKです。

動作確認

あるプロジェクトフォルダを対象に動作確認をします。

まずはPython 3.10.11をベースにします。

pyenv install 3.10.11

# :: [Info] ::  Mirror: https://www.python.org/ftp/python
# :: [Downloading] ::  3.10.11 ...
# :: [Downloading] ::  From https://www.python.org/ftp/python/3.10.11/python-3.10.11-amd64.exe
# :: [Downloading] ::  To   C:\Users\{ご自身のユーザ名}\.pyenv\pyenv-win\install_cache\python-3.10.11-amd64.exe
# :: [Installing] ::  3.10.11 ...
# :: [Info] :: completed! 3.10.11

次に、プロジェクトフォルダに移動して、pyenvの設定を行います。

mkdir -p my-project
cd ./my-project
pyenv local 3.10.11

poetryで初期化を行います。

poetry init

# This command will guide you through creating your pyproject.toml config.
#
# Package name [my-project]:
# Version [0.1.0]:
# Description []:
# Author [unknown <example@example.com>, n to skip]:  n
# License []:
# Compatible Python versions [^3.12]:  3.10.11
#
# 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 = "sample"
# version = "0.1.0"
# description = ""
# authors = ["Your Name <you@example.com>"]
# readme = "README.md"
#
# [tool.poetry.dependencies]
# python = "3.10.11"
#
#
# [build-system]
# requires = ["poetry-core"]
# build-backend = "poetry.core.masonry.api"
#
#
# Do you confirm generation? (yes/no) [yes]

念のためPythonの実行ファイルがpyenvを指していることを確認し、

python -c "import sys; print(sys.executable)"

# C:\Users\{ご自身のユーザ名}\.pyenv\pyenv-win\versions\3.10.11\python.exe

env useで使用するPython実行ファイルを設定します。

poetry env use python

# Creating virtualenv sample-GJM0V5El-py3.10 in C:\Users\{ご自身のユーザ名}\AppData\Local\pypoetry\Cache\virtualenvs
# Using virtualenv: C:\Users\{ご自身のユーザ名}\AppData\Local\pypoetry\Cache\virtualenvs\sample-GJM0V5El-py3.10

最後に、poetry環境のshellに入り、

poetry shell

# Virtual environment already activated: C:\Users\{ご自身のユーザ名}\AppData\Local\pypoetry\Cache\virtualenvs\sample-GJM0V5El-py3.10

Pythonの実行を確認します。

python

# Python 3.10.11 (tags/v3.10.11:7d4cc5a, Apr  5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)] on win32
# Type "help", "copyright", "credits" or "license" for more information.
# >>>

参考

pyenvやpoetryの細かい使い方は公式ドキュメントや過去記事を参照ください。

まとめ

いかがでしたでしょうか。本記事がPythonを使用される方の参考になれば幸いです。