Hướng dẫn python3 venv - python3 venv

Nội dung

  • 1.Giới thiệu Virtual Environment trong Python
  • 2. Cài đặt và sử dụng Virtual environment
    • 2.1 Cài đặt virtualenv
    • 2.2 Tạo môi trường ảo
    • 2.3 Khởi động môi trường ảo
    • 2.4 Tắt môi trường ảo
    • 2.5 Xuất các package đã cài đặt
    • 2.6 Nhập các package

1.Giới thiệu Virtual Environment trong Python

2. Cài đặt và sử dụng Virtual environmentpython là môi trường ảo. Cũng giống như máy ảo [Virtual Machine], Virtual Environment thiết lập một môi trường ảo, cho phép bạn thoải mái thực hiện cài đặt rồi xóa, cài đặt các phiên bản khác nhau với các packages của Python mà không sợ làm ảnh hưởng đến những dự án đang có sẵn.

2. Cài đặt và sử dụng Virtual environment

2.1 Cài đặt virtualenv
virtualenv là công cụ tiêu chuẩn trong nhiều năm, có thể được sử dụng với cả Python 2 và 3.
venv [pyvenv] được thêm vào thư viện chuẩn trong Python 3.3.

2.2 Tạo môi trường ảovirtualenv.

2.1 Cài đặt virtualenvvirtualenv

2.2 Tạo môi trường ảo
pip install virtualenv

2.2 Tạo môi trường ảo

2.3 Khởi động môi trường ảovritualenv python_env để khởi tạo môi trường ảo.

2.4 Tắt môi trường ảopython_env là tên đường dẫn chứa Virtual Environment cho dự án của bạn.

2.3 Khởi động môi trường ảo

2.4 Tắt môi trường ảosource python_env/bin/activate

2.5 Xuất các package đã cài đặt[python_env]

2.4 Tắt môi trường ảo

2.5 Xuất các package đã cài đặt

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

2.5 Xuất các package đã cài đặt

2.6 Nhập các package

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

2.6 Nhập các package

Virtual Environment trong python là môi trường ảo. Cũng giống như máy ảo [Virtual Machine], Virtual Environment thiết lập một môi trường ảo, cho phép bạn thoải mái thực hiện cài đặt rồi xóa, cài đặt các phiên bản khác nhau với các packages của Python mà không sợ làm ảnh hưởng đến những dự án đang có sẵn.

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

Có hai công cụ chính được sử dụng để tạo môi trường ảo: • virtualenv là công cụ tiêu chuẩn trong nhiều năm, có thể được sử dụng với cả Python 2 và 3. • venv [pyvenv] được thêm vào thư viện chuẩn trong Python 3.3.

Trong bài viết này chúng ta sẽ sử dụng virtualenv.

Để cài đặt virtualenv chúng ta sử dụng lệnh sau:pip install virtualenv

Tiếp đến chúng ta sử dụng lệnh vritualenv python_env để khởi tạo môi trường ảo.
Cloud Server
Cloud Server Pro
Máy Chủ Riêng

Trong đó python_env là tên đường dẫn chứa Virtual Environment cho dự án của bạn.

Mới trong phiên bản 3.3.

Đã thay đổi trong phiên bản 3.4: Đã thêm tham số source0 Lib/venv/

Đã thay đổi trong phiên bản 3.6: Đã thêm tham số source3

Đã thay đổi trong phiên bản 3.9: Đã thêm tham số source6

Một ví dụ về việc mở rộng ____ 72¶PEP 405 for more background on Python virtual environments.

Tập lệnh sau đây cho thấy cách mở rộng vritualenv python_env2 bằng cách triển khai một lớp con cài đặt setuptools và pip vào môi trường ảo được tạo:: not Emscripten, not WASI.

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 = '//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 = '//bootstrap.pypa.io/get-pip.py'
        self.install_script[context, 'pip', url]

def main[args=None]:
    compatible = True
    if sys.version_info c:\Python35\python -m venv c:\path\to\myenv
3:

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

Mô -đun

c:\>c:\Python35\python -m venv c:\path\to\myenv
3 hỗ trợ tạo ra các môi trường ảo nhẹ, mỗi bộ có bộ gói Python độc lập riêng được cài đặt trong các thư mục
c:\>c:\Python35\python -m venv c:\path\to\myenv
4 của họ. Một môi trường ảo được tạo ra trên đầu cài đặt Python hiện có, được gọi là môi trường ảo, cơ sở của Python, và có thể được phân lập từ các gói trong môi trường cơ sở, do đó, chỉ có những gói được cài đặt rõ ràng trong môi trường ảo.

Đã không dùng nữa vì phiên bản 3.6:

c:\>python -m venv c:\path\to\myenv
5 là công cụ được đề xuất để tạo môi trường ảo cho Python 3.3 và 3,4, và không được dùng trong Python 3.6.
c:\>python -m venv c:\path\to\myenv
5 was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6.

Đã thay đổi trong phiên bản 3.5: Việc sử dụng

c:\>c:\Python35\python -m venv c:\path\to\myenv
3 hiện được khuyến nghị để tạo môi trường ảo.The use of
c:\>c:\Python35\python -m venv c:\path\to\myenv
3 is now recommended for creating virtual environments.

Trên Windows, gọi lệnh

c:\>c:\Python35\python -m venv c:\path\to\myenv
3 như sau:

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

Ngoài ra, nếu bạn đã cấu hình các biến

c:\>python -m venv c:\path\to\myenv
8 và
c:\>python -m venv c:\path\to\myenv
9 cho cài đặt Python của bạn:Python installation:

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

Lệnh, nếu chạy với

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
0, sẽ hiển thị các tùy chọn có sẵn:

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

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

Đã thay đổi trong phiên bản 3.9: Thêm tùy chọn

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
1 để nâng cấp PIP + setuptools lên mới nhất trên PYPIAdd
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
1 option to upgrade pip + setuptools to the latest on PyPI

Đã thay đổi trong phiên bản 3.4: Cài đặt PIP theo mặc định, đã thêm các tùy chọn

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
2 và
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
3Installs pip by default, added the
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
2 and
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

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

Đã thay đổi trong phiên bản 3.4: Trong các phiên bản trước, nếu thư mục đích đã tồn tại, lỗi đã được nêu ra, trừ khi tùy chọn

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
4 hoặc
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
5 được cung cấp.In earlier versions, if the target directory already existed, an error was raised, unless the
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
4 or
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

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

Ghi chú

Mặc dù các liên kết symlink được hỗ trợ trên Windows, nhưng chúng không được khuyến khích. Đặc biệt lưu ý là việc nhấp đúp vào

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
6 trong File Explorer sẽ giải quyết Symlink một cách háo hức và bỏ qua môi trường ảo.

Ghi chú

Mặc dù các liên kết symlink được hỗ trợ trên Windows, nhưng chúng không được khuyến khích. Đặc biệt lưu ý là việc nhấp đúp vào

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
6 trong File Explorer sẽ giải quyết Symlink một cách háo hức và bỏ qua môi trường ảo.

Trên Microsoft Windows, có thể cần phải bật tập lệnh

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
7 bằng cách đặt chính sách thực thi cho người dùng. Bạn có thể làm điều này bằng cách ban hành lệnh PowerShell sau:

PS C:> Set -ExecutionPolicy -executpolicy RemoteSign -scope CurrentUser

Xem về chính sách thực thi để biết thêm thông tin.

Tệp

c:\>c:\Python35\python -m venv c:\path\to\myenv
8 được tạo cũng bao gồm khóa
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
9, được đặt thành
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]
0 nếu
c:\>c:\Python35\python -m venv c:\path\to\myenv
3 được chạy với tùy chọn
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]
2,
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]
3 nếu không.

Trừ khi tùy chọn

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            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.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
2 được đưa ra,
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]
5 sẽ được gọi cho bootstrap
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]
6 vào môi trường ảo.

Nhiều đường dẫn có thể được đưa ra cho
c:\>c:\Python35\python -m venv c:\path\to\myenv
3, trong trường hợp đó, một môi trường ảo giống hệt nhau sẽ được tạo ra, theo các tùy chọn đã cho, tại mỗi đường dẫn được cung cấp.

Cách VENVS hoạt động trong đó

Khi một thông dịch viên Python chạy từ môi trường ảo,

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]
8 và
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]
9 chỉ vào các thư mục của môi trường ảo, trong khi
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 = '//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 = '//bootstrap.pypa.io/get-pip.py'
        self.install_script[context, 'pip', url]

def main[args=None]:
    compatible = True
    if sys.version_info 

Bài Viết Liên Quan

Chủ Đề