R.A. Epigonos et al.

[python] venvで仮想環境

例えば、システムのパッケージ管理システム(apt)に必要なモジュールがない、システムの環境を汚したくない、最新のパッケージを使いたい、などの場合に仮想環境を。

仮想環境の作成に必要なvenvパッケージをシステムにインストールし、venv環境を作る。


$ sudo apt-get install python3-venv
$ mkdir --parents /path/to/venv/repository
$ cd /path/to/venv/repository
$ python -m venv sandbox

作った仮想環境をactivateすると、pythonとかpipのコマンドが仮想環境のものに置き換えられる。


$ . /path/to/venv/repository/bin/activate
(sandbox) $ which python
/path/to/venv/repository/sandbox/bin/python
(sandbox) $ which pip
/path/to/venv/repository/sandbox/bin/pip
(sandbox) $ pip install numpy
(sandbox) $ python
Python 3.11.2 (main, Nov 30 2024, 21:22:50) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> numpy.__version__
'2.2.3'
>>> quit()
(sandbox) $ deactivate

仮想環境で動作するプログラムを外から実行するには

1つ目は、venv環境に入るラッパーを作ってその中でpython実行ファイルを呼ぶ方法。


$ cat hoge.py.sh
#!/bin/sh
set -eux;

. /path/to/venv/repository/bin/activate

python3 /path/to/hoge.py $@

deactivate
exit
$ hoge.py.sh --option

2つ目は、venv内のpython実行ファイルにプログラムファイルを渡す方法。この方法は環境変数を設定しないため、プログラム内で起動した別プロセスはvenv環境の外で実行される。


$ /path/to/venv/repository/sandbox/bin/python hoge.py --option
If you directly run a script or the python interpreter from the virtualenv’s bin/ directory (e.g. path/to/ENV/bin/pip or /path/to/ENV/bin/python-script.py) then sys.path will automatically be set to use the Python libraries associated with the virtualenv. But, unlike the activation scripts, the environment variables PATH and VIRTUAL_ENV will not be modified. This means that if your Python script uses e.g. subprocess to run another Python script (e.g. via a #!/usr/bin/env python shebang line) the second script may not be executed with the same Python binary as the first nor have the same libraries available to it. To avoid this happening your first script will need to modify the environment variables in the same manner as the activation scripts, before the second script is executed.
virtualenv の bin/ ディレクトリからスクリプトや python インタプリタを直接実行した場合 (例: path/to/ENV/bin/pip や /path/to/ENV/bin/python-script.py) 、sys.path は自動的に virtualenv に関連付けられた Python ライブラリを使用するように設定されます。しかし、起動スクリプトとは異なり、環境変数 PATH と VIRTUAL_ENV は変更されません。このことは、Pythonスクリプトが例えばサブプロセスを使って別のPythonスクリプトを実行する場合(例えば #!/usr/bin/env python shebang 行で)、2番目のスクリプトは最初のスクリプトと同じPythonバイナリで実行されず、同じライブラリも利用できない可能性があることを意味します。このような事態を避けるために、2つ目のスクリプトが実行される前に、1つ目のスクリプトは起動スクリプトと同じ方法で環境変数を変更する必要があります。

リファレンス

  1. User Guide — virtualenv 16.7.9 documentation
  2. python - Running script without virtualenv activation - Stack Overflow

ソーシャルブックマーク

  1. はてなブックマーク
  2. Google Bookmarks
  3. del.icio.us

ChangeLog

  1. Posted: 2010-10-06T11:35:10+09:00
  2. Modified: 2010-10-06T11:35:10+09:00
  3. Generated: 2025-02-17T23:09:14+09:00