Python基礎

もう壊れないPython環境:venv×pip-toolsで作る再現可能な依存管理

仮想環境や依存関係、気づくと壊れていませんか?「昨日は動いたのに、今日は動かない…」

軽くて再現性が高く、アップデートもしやすい“ちょうど良い運用”が知りたい!

答えはシンプルです。venv × pip-toolsrequirements.inpip-compilepip-sync)で、再現性×更新容易性×安全性を一気に揃えましょう。本記事ではセットアップから運用、更新、トラブル救急箱まで“コピペでOK”で解説します。

この記事で身に付く力

  • “宣言(.in)”と“施行(.txt)”を分ける再現可能な依存管理
  • 本番・開発を分けた4ファイル構成と安全な更新手順
  • オフラインや社内PCでも配布できる仕組み(wheelhouse)
  • Docker / CI / Colabとの連携の型

仮想環境と依存関係管理:pip-tools/requirementsの基礎

いちばん事故が起きやすいのは依存関係。「ローカルでは動くのに他のPCで落ちる」「pip installを重ねて太る」「pip freezeだけ配って再現できない」。——これらはすべて“宣言”と“施行”が混ざっていることが原因です。

解決策は、.in(宣言:意図)と.txt(施行:固定結果)を分け、pip-syncで環境を完全一致させること。ここからは、最短10分で整う手順を紹介します。

ふみとの現場メモ

5人チームで分析基盤を立ち上げたとき、pip-toolsに切り替えただけで「動かない」がゼロに。requirements.txtの差分だけレビューすればよくなり、レビュー時間は半分以下になりました。

10分クイックスタート(コピペOK)

# 0) 仮想環境の作成と有効化
python -m venv .venv
# Windows PowerShell
.\.venv\Scripts\Activate.ps1
# macOS/Linux
source .venv/bin/activate

# 1) pip-tools を導入

python -m pip install -U pip
pip install pip-tools

# 2) 要件を .in に書く(例)

printf "pandas\nmatplotlib\njupyter\n" > requirements.in

# 3) 依存をロック(ハッシュ付き推奨)

pip-compile -o requirements.txt --generate-hashes requirements.in

# 4) 環境を同期(.txt どおりに揃える)

pip-sync requirements.txt

# 5) Jupyterカーネル登録(任意)

pip install ipykernel && python -m ipykernel install --user --name proj --display-name "Python (proj)"

原則:インストールは常にpip-sync。何か入れたいときは.inを編集 → pip-compileしてから。

.in / .txt / constraintsの役割

基本は2ファイル。宣言(意図)はrequirements.in、施行(固定結果)はrequirements.txtです。

requirements.in      # 宣言:上位依存だけ(意図)
requirements.txt     # 施行:全依存を固定(結果)
constraints.txt      # 任意:問題版のピン止め・除外

.inには「使うライブラリだけ」を記述(例:pandas>=2.2,<2.3)。.txtはコンパイル結果なので直編集しません。既知の不具合を避けたい場合はconstraints.txtを併用します。

# constraintsを効かせてコンパイル
pip-compile -o requirements.txt --generate-hashes -c constraints.txt requirements.in

# 例: constraints.txt

# numpy!=2.0.0

おすすめ構成:本番と開発を分ける4ファイル

requirements.in          # 本番/実行時(ランタイム)
requirements-dev.in      # 開発ツール(black/ruff/pytest など)
requirements.txt         # 本番ロック
requirements-dev.txt     # 開発ロック(本番+開発)
pip-compile -o requirements.txt --generate-hashes requirements.in
pip-compile -o requirements-dev.txt --generate-hashes requirements-dev.in -r requirements.txt

-r requirements.txt本番依存を取り込んだ上で開発ロックを作れます。

バージョン設計のコツ

アプリや分析ノートは本番を完全固定(.txt).in>=,<で許容範囲を持たせ、定期的に再コンパイル。配布用ライブラリは別途pyproject.tomlで緩やかに指定。OS依存は環境マーカー(例:pywin32; platform_system == "Windows")。

安全にアップデートするワークフロー

# 影響を確認
pip-compile --upgrade --dry-run requirements.in

# 実施(本番)

pip-compile --upgrade -o requirements.txt --generate-hashes requirements.in
pip-sync requirements.txt

# 開発も更新

pip-compile --upgrade -o requirements-dev.txt --generate-hashes requirements-dev.in -r requirements.txt
pip-sync requirements-dev.txt

PRではrequirements*.txt差分だけを見るとレビューが速いです。万一のときは.txtgit revertすれば環境も元に戻ります。

VSCode/タスク/Makefileで“1キー運用”

install:
	python -m pip install -U pip && pip install pip-tools
	pip-compile -o requirements.txt --generate-hashes requirements.in
	pip-sync requirements.txt

install-dev:
pip-compile -o requirements-dev.txt --generate-hashes requirements-dev.in -r requirements.txt
pip-sync requirements-dev.txt

update:
pip-compile --upgrade -o requirements.txt --generate-hashes requirements.in
pip-compile --upgrade -o requirements-dev.txt --generate-hashes requirements-dev.in -r requirements.txt

outdated:
pip list --outdated

Windowsは[内部リンク:作業時間を半減する環境構築:VSCode/タスクランナー]で同等タスクを登録しておくと快適です。

オフライン/社内PCでの配布(wheelhouse)

# 事前にホイールをまとめる
pip wheel -r requirements.txt -w wheelhouse

# オフライン先でインストール

pip install --no-index --find-links=wheelhouse -r requirements.txt

社内共有のwheelhouseを用意すると高速&安定。プロキシや証明書はpip.ini/pip.confで設定(ITポリシーに従う)。

セキュリティの基本

--generate-hashesで改ざん検知(sha256.txtに入る)。APIキーや個人情報はrequirementsに書かないで、.env管理。

Docker / CI / Colab 連携

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt ./
RUN python -m pip install -U pip && pip install -r requirements.txt
COPY . .
- uses: actions/setup-python@v5
  with:
    python-version: '3.12'
- run: pip install pip-tools
- run: pip-sync requirements.txt
- run: pytest -q

Colabは学習時に.inpip install -q -rで使い、再現が必要な実験では.txtを使うのが簡便です。

トラブル救急箱

  • pip-sync後にImportError.inへの書き忘れ。.inに追記→再compilesync
  • Windowsでビルドエラー(GDAL等):Condaへ切替 or 事前ビルドwheelを利用。
  • pip-compileが解決不能:バージョン範囲の衝突。.inの範囲を緩める or constraintsでピン止め。
  • カーネルが増えすぎjupyter kernelspec list→不要をjupyter kernelspec remove <name>
  • pip freezeの環境を移行:freeze一覧から「実際に使うもの」だけを.inへ抽出→compile

ミニテンプレート(コピペでどうぞ)

pandas>=2.2,<2.3
matplotlib>=3.8,<3.9
jupyter>=1.0
pyarrow>=16,<17
-r requirements.txt
black>=24.4
ruff>=0.5
pytest>=8.3
pre-commit>=3.7
# Known bad versions (example)
numpy!=2.0.0
### Setup
python -m venv .venv && source .venv/bin/activate  # WindowsはActivate.ps1
python -m pip install -U pip && pip install pip-tools
pip-compile -o requirements.txt --generate-hashes requirements.in
pip-sync requirements.txt

今日やること(30〜45分)

  1. python -m venv .venvpip install pip-tools
  2. .in/.txtの2枚pip-syncで“再現できる環境”を体感。
  3. 4ファイル構成に拡張し、Make/Tasksを登録。
  4. 週1でpip-compile --upgrade→PRで差分レビュー

次に読むべきもの(内部リンク)

超入門
【超入門】最短30分で動くPython環境|公式版+venv+VSCodeでHello WorldとJupyterまで

最短30分で「Pythonが動く」環境をつくる。 公式インストーラ+venv+VSCodeの軽い正攻法で、Hello WorldとJupyterまでコピペで到達します。 この記事のゴール Window ...

Python環境
Python環境構築の最適解:venv・pip・Condaの使い分け【保存版】

Pythonの環境づくり、結局「venv」「pip」「Anaconda(Conda)」のどれから始めればいいの? 最短で沼らず、あとから壊れないやり方が知りたい…! そんなモヤモヤを一気に解決するため ...

Jupyter Notebookの基本
【保存版】Jupyter Notebookの基本:環境構築・使い方・再現性・“読みやすいノート”設計まで完全ガイド

Jupyter Notebookは学習・検証・共有に最強の道具ですが、設計を間違えると再現できない・読みにくい・遅いノートになってしまいます。本記事は、未経験〜初学者が週10時間×1〜2週で、環境構築 ...

作業時間短縮
作業時間を半減する環境構築:VSCode/タスクランナー|“保存で整う・ワンキーで回る”仕組み化テンプレ

結論:副業でも本業でも、作業時間の半分は“環境と段取り”で削れます。カギは ①保存で自動整形/静的解析、②ワンキーで一連実行(lint→test→report)、③再現性の担保(venv/pip-to ...

テスト
【コピペOK】pytestで“壊れないPython”を作る12ステップ

「昨日は動いてたのに、今日は壊れた…」 データ分析やETL、機械学習のコードで多発するこの悲劇。実は“テスト不在”が9割です。 本記事は、pytestで“壊れないPython”を作るための実務ガイド。 ...

PCスペック
低スペックPCでも学べる?クラウド環境の使い方|“端末は薄く、環境は雲へ”の実践ガイド

PCが古い/非力で、学習や実務を諦めていませんか? 結論:処理を雲側に寄せれば、低スペPCでも十分に戦えます。 この記事で身に付く力 Colab/Kaggle/Codespacesで“雲寄せ”する実務 ...

無料カウンセリングのご案内

依存は設計と言語化で安定します。案件に合わせた4ファイル構成CI/オフライン配布まで、一緒に整えましょう。

TechAcademy データサイエンスコース(受講料:174,600円~ ※更に割引あり)

TechAcademy 無料相談

株式会社キカガク AI人材長期育成コース(受講料:237,600円~)

キカガク 無料相談

まとめ

venv × pip-toolsは、軽く・再現性が高く・安全に運用できるベストプラクティスです。.inで意図を宣言し、.txtで結果を固定、pip-syncで唯一の真実に揃える。まずはクイックスタートをコピペして、今日から依存の悩みを終わらせましょう。

最近のコメント

    • この記事を書いた人
    • 最新記事

    ふみと

    このブログでは、データサイエンティストとして市場価値を上げる方法を独自にまとめて発信しています。

    【プロフィール】
    ・大手企業データサイエンティスト/マーケティングサイエンティスト(10年、年収900万円台)/案件100件以上
    ・資格:JDLA E資格(日本ディープラーニング協会主催)/JDLA Community(CDLE会員)/Advanced Marketer/ビジネス統計スペシャリスト/統計検定2級/TOEIC 805
    ・スキル:Python/Tableau/SQL/機械学習/Deep Learning/RPA

    -Python基礎