1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの仮想環境の構築

1
Last updated at Posted at 2024-12-24

はじめに

Pythonでプロジェクトを開発する際には、仮想環境を構築することで、プロジェクトごとに別々のライブラリを使えるようになります。これにより、別のプロジェクトの依存関係が交互に崩れるのを防ぎ、環境の混乱を避けることができます。

本記事では、Pythonの仮想環境の構築方法を解説します。

仮想環境の作成

仮想環境を作成するには、Pythonに含まれる「venv」モジュールを使用します。

仮想環境の構築
python -m venv 仮想環境名

次に「.venv」という名前の仮想環境を構築する具体例を示します。

仮想環境の構築(具体例)
python -m venv .venv

有効化

作成した仮想環境を有効にするためには、次のコマンドを実行します。

.\.venv\Scripts\activate

上記のコマンドをお使いのマシン環境で初めて実行された場合(特にVSCode上のターミナル)、次のエラーが出力されることがあります。

.\.venv\Scripts\activate : このシステムではスクリプトの実行が無効になっているため、ファイル C:~省略~\.venv\Scripts\Activate.p
s1 を読み込むことができません。詳細については、「about_Execution_Policies」(https://go.microsoft.com/fwlink/?LinkID=135170) を参照してください。
発生場所 行:1 文字:1
+ .\.venv\Scripts\activate
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : セキュリティ エラー: (: ) []、PSSecurityException

その場合、次のコマンドで、PowerShellの実行ポリシーを変更する必要があります。

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force

使用例

全体の工程をまとめると、次のようになります。

# 仮想環境の構築と有効化
python -m venv .venv
.\.venv\Scripts\activate

# 使用するライブラリのインストール
pip install -r .\requirements.txt

なお、次のコマンドを実行すると、requirements.txt の内容が上書きされます。

ライブラリリストの更新
pip freeze > requirements.txt

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?