venv —仮想環境の作成—Pythonドキュメント

提供:Dev Guides
< PythonPython/docs/3.8/library/venv
移動先:案内検索

venv —仮想環境の作成

バージョン3.3の新機能。


ソースコード: :source: `Lib / venv /`



venv モジュールは、独自のサイトディレクトリを使用して軽量の「仮想環境」を作成するためのサポートを提供します。オプションでシステムサイトディレクトリから分離されます。 各仮想環境には独自のPythonバイナリ(この環境の作成に使用されたバイナリのバージョンと一致)があり、サイトディレクトリに独自の独立したPythonパッケージのセットをインストールできます。

Python仮想環境の詳細については、 PEP 405 を参照してください。

仮想環境の作成

仮想環境の作成は、コマンドvenvを実行することによって実行されます。

python3 -m venv /path/to/new/virtual/environment

このコマンドを実行すると、ターゲットディレクトリが作成され(まだ存在しない親ディレクトリが作成されます)、コマンドの元となったPythonインストールを指すhomeキーが付いたpyvenv.cfgファイルがその中に配置されます。 run(ターゲットディレクトリの一般名は.venvです)。 また、Pythonバイナリ/バイナリのコピー/シンボリックリンクを含むbin(またはWindowsではScripts)サブディレクトリを作成します(環境の作成時に使用されるプラットフォームまたは引数に応じて)。 また、(最初は空の)lib/pythonX.Y/site-packagesサブディレクトリを作成します(Windowsでは、これはLib\site-packagesです)。 既存のディレクトリを指定すると、再利用されます。

バージョン3.6以降非推奨: pyvenvはPython3.3および3.4の仮想環境を作成するための推奨ツールであり、Python 3.6 では非推奨です。


バージョン3.5で変更:仮想環境の作成にはvenvの使用が推奨されるようになりました。


Windowsでは、次のようにvenvコマンドを呼び出します。

c:\>c:\Python35\python -m venv c:\path\to\myenv

または、 Pythonインストール用にPATH変数とPATHEXT変数を構成した場合:

c:\>python -m venv c:\path\to\myenv

コマンドを-hで実行すると、使用可能なオプションが表示されます。

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT]
            ENV_DIR [ENV_DIR ...]

Creates virtual Python environments in one or more target directories.

positional arguments:
  ENV_DIR               A directory to create the environment in.

optional arguments:
  -h, --help            show this help message and exit
  --system-site-packages
                        Give the virtual environment access to the system
                        site-packages dir.
  --symlinks            Try to use symlinks rather than copies, when symlinks
                        are not the default for the platform.
  --copies              Try to use copies rather than symlinks, even when
                        symlinks are the default for the platform.
  --clear               Delete the contents of the environment directory if it
                        already exists, before environment creation.
  --upgrade             Upgrade the environment directory to use this version
                        of Python, assuming Python has been upgraded in-place.
  --without-pip         Skips installing or upgrading pip in the virtual
                        environment (pip is bootstrapped by default)
  --prompt PROMPT       Provides an alternative prompt prefix for this
                        environment.

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.

バージョン3.4で変更:デフォルトでpipをインストールし、--without-pipおよび--copiesオプションを追加


バージョン3.4で変更:以前のバージョンでは、ターゲットディレクトリがすでに存在する場合、--clearまたは--upgradeオプションが指定されていない限り、エラーが発生しました。


ノート

シンボリックリンクはWindowsでサポートされていますが、お勧めしません。 特に注意すべきは、ファイルエクスプローラーでpython.exeをダブルクリックすると、シンボリックリンクが熱心に解決され、仮想環境が無視されることです。


ノート

Microsoft Windowsでは、ユーザーの実行ポリシーを設定して、Activate.ps1スクリプトを有効にする必要がある場合があります。 これを行うには、次のPowerShellコマンドを発行します。

PS C:> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

詳細については、実行ポリシーについてを参照してください。


作成されたpyvenv.cfgファイルにはinclude-system-site-packagesキーも含まれており、venv--system-site-packagesオプションfalseそれ以外の場合。

--without-pipオプションが指定されていない限り、 surepip が呼び出され、pipが仮想環境にブートストラップされます。

venvに複数のパスを指定できます。その場合、指定されたオプションに従って、指定された各パスに同一の仮想環境が作成されます。

仮想環境が作成されると、仮想環境のバイナリディレクトリにあるスクリプトを使用して「アクティブ化」できます。 スクリプトの呼び出しはプラットフォーム固有です( 仮想環境を含むディレクトリのパスに置き換える必要があります):

プラットホーム シェル 仮想環境をアクティブ化するコマンド
POSIX bash / zsh $ソース / bin / activate
$ . /bin/activate.fish
csh / tcsh $ソース /bin/activate.csh
PowerShellコア $ /bin/Activate.ps1
ウィンドウズ cmd.exe C:\> \ Scripts \ activate.bat
パワーシェル PS C:\> \ Scripts \ Activate.ps1

仮想環境がアクティブな場合、 VIRTUAL_ENV環境変数が仮想環境のパスに設定されます。 これを使用して、仮想環境内で実行されているかどうかを確認できます。

環境をアクティブ化するために特に必要はありません。 アクティベーションは、仮想環境のバイナリディレクトリをパスの前に追加するだけなので、「python」は仮想環境のPythonインタープリターを呼び出し、インストールされたスクリプトをフルパスを使用せずに実行できます。 ただし、仮想環境にインストールされたすべてのスクリプトは、アクティブ化せずに実行可能であり、仮想環境のPythonで自動的に実行される必要があります。

シェルで「deactivate」と入力すると、仮想環境を非アクティブ化できます。 正確なメカニズムはプラットフォーム固有であり、内部実装の詳細です(通常はスクリプトまたはシェル関数が使用されます)。

バージョン3.4の新機能: fishおよびcshアクティベーションスクリプト。


バージョン3.8の新機能: PowerShellCoreサポート用にPOSIXの下にインストールされたPowerShellアクティベーションスクリプト。


ノート

仮想環境は、Pythonインタープリター、それにインストールされているライブラリ、スクリプトが他の仮想環境にインストールされているもの、および(デフォルトで)「システム」Pythonにインストールされているライブラリ、つまりインストールされているライブラリから分離されているPython環境です。オペレーティングシステムの一部として。

仮想環境は、Python実行可能ファイルおよび仮想環境であることを示すその他のファイルを含むディレクトリツリーです。

setuptoolspip などの一般的なインストールツールは、仮想環境で期待どおりに機能します。 つまり、仮想環境がアクティブな場合、明示的に指示する必要なしに、Pythonパッケージを仮想環境にインストールします。

仮想環境がアクティブな場合(つまり、仮想環境のPythonインタープリターが実行されている場合)、属性 sys.prefix および sys.exec_prefix は仮想環境のベースディレクトリを指しますが、 sys.base_prefix および sys.base_exec_prefix は、仮想環境の作成に使用された非仮想環境Pythonインストールを指します。 仮想環境がアクティブでない場合、 sys.prefixsys.base_prefix と同じであり、 sys.exec_prefixsysと同じです。 base_exec_prefix (これらはすべて非仮想環境のPythonインストールを指します)。

仮想環境がアクティブな場合、プロジェクトが仮想環境の外部に誤ってインストールされるのを防ぐために、インストールパスを変更するオプションはすべての distutils 構成ファイルから無視されます。

コマンドシェルで作業する場合、ユーザーは仮想環境の実行可能ディレクトリでactivateスクリプトを実行することにより、仮想環境をアクティブにすることができます(ファイルを使用する正確なファイル名とコマンドはシェルによって異なります)。実行中のシェルのPATH環境変数への実行可能ファイルの環境ディレクトリ。 他の状況では、仮想環境をアクティブ化する必要はありません。 仮想環境にインストールされたスクリプトには、仮想環境のPythonインタープリターを指す「シバン」行があります。 これは、PATHの値に関係なく、スクリプトがそのインタープリターで実行されることを意味します。 Windowsでは、Python Launcher for Windowsがインストールされている場合、「シバン」行処理がサポートされます(これは、3.3でPythonに追加されました。詳細については、 PEP 397 を参照してください)。 したがって、Windowsエクスプローラーウィンドウでインストールされたスクリプトをダブルクリックすると、PATHの仮想環境への参照がなくても、正しいインタープリターでスクリプトを実行できます。


API

上記の高レベルのメソッドは、サードパーティの仮想環境作成者がニーズに応じて環境作成をカスタマイズするためのメカニズムである EnvBuilder クラスを提供する単純なAPIを利用します。

class venv.EnvBuilder(system_site_packages=False, clear=False, symlinks=False, upgrade=False, with_pip=False, prompt=None)

EnvBuilder クラスは、インスタンス化時に次のキーワード引数を受け入れます。

  • system_site_packages –システムPythonサイトパッケージが環境で利用可能である必要があることを示すブール値(デフォルトはFalse)。

  • clear –ブール値。trueの場合、環境を作成する前に、既存のターゲットディレクトリの内容を削除します。

  • symlinks –コピーではなくPythonバイナリのシンボリックリンクを試みるかどうかを示すブール値。

  • upgrade –ブール値。trueの場合、実行中のPythonで既存の環境をアップグレードします–そのPythonがインプレースでアップグレードされたときに使用します(デフォルトはFalse)。

  • with_pip –ブール値。trueの場合、pipが仮想環境にインストールされていることを確認します。 これは、--default-pipオプションとともに ensurepip を使用します。

  • prompt –仮想環境がアクティブ化された後に使用される文字列(デフォルトはNoneで、環境のディレクトリ名が使用されることを意味します)。

バージョン3.4で変更: with_pipパラメーターを追加

バージョン3.6の新機能: promptパラメーターが追加されました

サードパーティの仮想環境ツールの作成者は、提供されている EnvBuilder クラスを基本クラスとして自由に使用できます。

返されるenv-builderは、メソッドcreateを持つオブジェクトです。

create(env_dir)

仮想環境を含めるターゲットディレクトリ(絶対または現在のディレクトリからの相対)を指定して、仮想環境を作成します。 createメソッドは、指定されたディレクトリに環境を作成するか、適切な例外を発生させます。

EnvBuilder クラスのcreateメソッドは、サブクラスのカスタマイズに使用できるフックを示しています。

def create(self, env_dir):
    """
    Create a virtualized Python environment in a directory.
    env_dir is the target directory to create an environment in.
    """
    env_dir = os.path.abspath(env_dir)
    context = self.ensure_directories(env_dir)
    self.create_configuration(context)
    self.setup_python(context)
    self.setup_scripts(context)
    self.post_setup(context)

各メソッド ensure_directories()create_configuration()setup_python()setup_scripts()post_setup() は上書きできます。

ensure_directories(env_dir)

環境ディレクトリと必要なすべてのディレクトリを作成し、コンテキストオブジェクトを返します。 これは、他のメソッドで使用するための属性(パスなど)の単なるホルダーです。 clearまたはupgradeのいずれかが既存の環境ディレクトリでの操作を許可するように指定されている限り、ディレクトリはすでに存在できます。

create_configuration(context)

環境内にpyvenv.cfg構成ファイルを作成します。

setup_python(context)

環境内のPython実行可能ファイルへのコピーまたはシンボリックリンクを作成します。 POSIXシステムでは、特定の実行可能ファイルpython3.xが使用された場合、それらの名前のファイルが既に存在しない限り、pythonおよびpython3へのシンボリックリンクがその実行可能ファイルを指すように作成されます。

setup_scripts(context)

プラットフォームに適したアクティベーションスクリプトを仮想環境にインストールします。

post_setup(context)

サードパーティの実装でオーバーライドして、仮想環境にパッケージをプレインストールしたり、その他の作成後の手順を実行したりできるプレースホルダーメソッド。

バージョン3.7.2で変更: Windowsは、実際のバイナリをコピーする代わりに、python[w].exeのリダイレクタスクリプトを使用するようになりました。 3.7.2では、 setup_python()のみが、ソースツリーのビルドから実行されない限り何もしません。

バージョン3.7.3で変更: Windowsは、 setup_scripts()ではなく setup_python()の一部としてリダイレクタスクリプトをコピーします。 これは3.7.2では当てはまりませんでした。 シンボリックリンクを使用すると、元の実行可能ファイルがリンクされます。

さらに、 EnvBuilder は、サブクラスの setup_scripts()または post_setup()から呼び出すことができるこのユーティリティメソッドを提供し、仮想環境へのカスタムスクリプトのインストールを支援します。 。

install_scripts(context, path)

path は、サブディレクトリ「common」、「posix」、「nt」を含むディレクトリへのパスであり、各サブディレクトリには、環境内のbinディレクトリ宛てのスクリプトが含まれています。 「common」の内容と os.name に対応するディレクトリは、プレースホルダーのテキスト置換後にコピーされます。

  • __VENV_DIR__は、環境ディレクトリの絶対パスに置き換えられます。

  • __VENV_NAME__は、環境名(環境ディレクトリの最終パスセグメント)に置き換えられます。

  • __VENV_PROMPT__はプロンプトに置き換えられます(環境名は括弧で囲まれ、次のスペースで囲まれます)

  • __VENV_BIN_NAME__は、binディレクトリの名前(binまたはScriptsのいずれか)に置き換えられます。

  • __VENV_PYTHON__は、環境の実行可能ファイルの絶対パスに置き換えられます。

ディレクトリは存在することが許可されています(既存の環境がアップグレードされている場合)。

モジュールレベルの便利な関数もあります。

venv.create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None)

指定されたキーワード引数を使用して EnvBuilder を作成し、 env_dir 引数を使用してその create()メソッドを呼び出します。

バージョン3.3の新機能。

バージョン3.4で変更: with_pipパラメーターを追加

バージョン3.6で変更: promptパラメーターを追加


EnvBuilderを拡張する例

次のスクリプトは、setuptoolsとpipを作成された仮想環境にインストールするサブクラスを実装することによって EnvBuilder を拡張する方法を示しています。

import os
import os.path
from subprocess import Popen, PIPE
import sys
from threading import Thread
from urllib.parse import urlparse
from urllib.request import urlretrieve
import venv

class ExtendedEnvBuilder(venv.EnvBuilder):
    """
    This builder installs setuptools and pip so that you can pip or
    easy_install other packages into the created virtual environment.

    :param nodist: If true, setuptools and pip are not installed into the
                   created virtual environment.
    :param nopip: If true, pip is not installed into the created
                  virtual environment.
    :param progress: If setuptools or pip are installed, the progress of the
                     installation can be monitored by passing a progress
                     callable. If specified, it is called with two
                     arguments: a string indicating some progress, and a
                     context indicating where the string is coming from.
                     The context argument can have one of three values:
                     'main', indicating that it is called from virtualize()
                     itself, and 'stdout' and 'stderr', which are obtained
                     by reading lines from the output streams of a subprocess
                     which is used to install the app.

                     If a callable is not specified, default progress
                     information is output to sys.stderr.
    """

    def __init__(self, *args, **kwargs):
        self.nodist = kwargs.pop('nodist', False)
        self.nopip = kwargs.pop('nopip', False)
        self.progress = kwargs.pop('progress', None)
        self.verbose = kwargs.pop('verbose', False)
        super().__init__(*args, **kwargs)

    def post_setup(self, context):
        """
        Set up any packages which need to be pre-installed into the
        virtual environment being created.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        os.environ['VIRTUAL_ENV'] = context.env_dir
        if not self.nodist:
            self.install_setuptools(context)
        # Can't install pip without setuptools
        if not self.nopip and not self.nodist:
            self.install_pip(context)

    def reader(self, stream, context):
        """
        Read lines from a subprocess' output stream and either pass to a progress
        callable (if specified) or write progress information to sys.stderr.
        """
        progress = self.progress
        while True:
            s = stream.readline()
            if not s:
                break
            if progress is not None:
                progress(s, context)
            else:
                if not self.verbose:
                    sys.stderr.write('.')
                else:
                    sys.stderr.write(s.decode('utf-8'))
                sys.stderr.flush()
        stream.close()

    def install_script(self, context, name, url):
        _, _, path, _, _, _ = urlparse(url)
        fn = os.path.split(path)[-1]
        binpath = context.bin_path
        distpath = os.path.join(binpath, fn)
        # Download script into the virtual environment's binaries folder
        urlretrieve(url, distpath)
        progress = self.progress
        if self.verbose:
            term = '\n'
        else:
            term = ''
        if progress is not None:
            progress('Installing %s ...%s' % (name, term), 'main')
        else:
            sys.stderr.write('Installing %s ...%s' % (name, term))
            sys.stderr.flush()
        # Install in the virtual environment
        args = [context.env_exe, fn]
        p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
        t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
        t1.start()
        t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
        t2.start()
        p.wait()
        t1.join()
        t2.join()
        if progress is not None:
            progress('done.', 'main')
        else:
            sys.stderr.write('done.\n')
        # Clean up - no longer needed
        os.unlink(distpath)

    def install_setuptools(self, context):
        """
        Install setuptools in the virtual environment.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
        self.install_script(context, 'setuptools', url)
        # clear up the setuptools archive which gets downloaded
        pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
        files = filter(pred, os.listdir(context.bin_path))
        for f in files:
            f = os.path.join(context.bin_path, f)
            os.unlink(f)

    def install_pip(self, context):
        """
        Install pip in the virtual environment.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        url = 'https://bootstrap.pypa.io/get-pip.py'
        self.install_script(context, 'pip', url)

def main(args=None):
    compatible = True
    if sys.version_info < (3, 3):
        compatible = False
    elif not hasattr(sys, 'base_prefix'):
        compatible = False
    if not compatible:
        raise ValueError('This script is only for use with '
                         'Python 3.3 or later')
    else:
        import argparse

        parser = argparse.ArgumentParser(prog=__name__,
                                         description='Creates virtual Python '
                                                     'environments in one or '
                                                     'more target '
                                                     'directories.')
        parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
                            help='A directory in which to create the
                                 'virtual environment.')
        parser.add_argument('--no-setuptools', default=False,
                            action='store_true', dest='nodist',
                            help="Don't install setuptools or pip in the "
                                 "virtual environment.")
        parser.add_argument('--no-pip', default=False,
                            action='store_true', dest='nopip',
                            help="Don't install pip in the virtual "
                                 "environment.")
        parser.add_argument('--system-site-packages', default=False,
                            action='store_true', dest='system_site',
                            help='Give the virtual environment access to the '
                                 'system site-packages dir.')
        if os.name == 'nt':
            use_symlinks = False
        else:
            use_symlinks = True
        parser.add_argument('--symlinks', default=use_symlinks,
                            action='store_true', dest='symlinks',
                            help='Try to use symlinks rather than copies, '
                                 'when symlinks are not the default for '
                                 'the platform.')
        parser.add_argument('--clear', default=False, action='store_true',
                            dest='clear', help='Delete the contents of the '
                                               'virtual environment '
                                               'directory if it already '
                                               'exists, before virtual '
                                               'environment creation.')
        parser.add_argument('--upgrade', default=False, action='store_true',
                            dest='upgrade', help='Upgrade the virtual '
                                                 'environment directory to '
                                                 'use this version of '
                                                 'Python, assuming Python '
                                                 'has been upgraded '
                                                 'in-place.')
        parser.add_argument('--verbose', default=False, action='store_true',
                            dest='verbose', help='Display the output '
                                               'from the scripts which '
                                               'install setuptools and pip.')
        options = parser.parse_args(args)
        if options.upgrade and options.clear:
            raise ValueError('you cannot supply --upgrade and --clear together.')
        builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
                                       clear=options.clear,
                                       symlinks=options.symlinks,
                                       upgrade=options.upgrade,
                                       nodist=options.nodist,
                                       nopip=options.nopip,
                                       verbose=options.verbose)
        for d in options.dirs:
            builder.create(d)

if __name__ == '__main__':
    rc = 1
    try:
        main()
        rc = 0
    except Exception as e:
        print('Error: %s' % e, file=sys.stderr)
    sys.exit(rc)

このスクリプトは、オンラインからダウンロードすることもできます。