Python 仮想環境の構築
仮想環境とは、プロジェクトごとに独立したPythonの実行環境を作る仕組みです。プロジェクトAとプロジェクトBで異なるバージョンのライブラリを使いたい場合でも、仮想環境を使えば互いに干渉しません。
ここでは、高速なパッケージ管理ツール uv を使って仮想環境を構築します。
1. uv のインストール
Section titled “1. uv のインストール”Windows (PowerShell)
Section titled “Windows (PowerShell)”powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"brew install uvWSL / Linux (Ubuntu)
Section titled “WSL / Linux (Ubuntu)”curl -LsSf https://astral.sh/uv/install.sh | shインストール後、ターミナルを再起動してから以下で確認します。
uv --version2. 仮想環境の作成
Section titled “2. 仮想環境の作成”プロジェクトのディレクトリで以下のコマンドを実行します。
uv venv実行すると .venv というフォルダが作成されます。
3. 仮想環境の有効化 (Activate)
Section titled “3. 仮想環境の有効化 (Activate)”Windows (PowerShell)
Section titled “Windows (PowerShell)”.\.venv\Scripts\Activate.ps1macOS / WSL / Linux
Section titled “macOS / WSL / Linux”source .venv/bin/activate有効化されると、プロンプトの先頭に (.venv) と表示されます。
4. パッケージのインストール
Section titled “4. パッケージのインストール”仮想環境を有効化した状態で、uv pip install でパッケージをインストールします。
uv pip install requests5. 仮想環境の解除 (Deactivate)
Section titled “5. 仮想環境の解除 (Deactivate)”OSに関わらず、同じコマンドで解除できます。
deactivate