Hướng dẫn python venv windows - cửa sổ python venv
Nội dung Show
1.Giới thiệu Virtual Environment trong Python2. 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 environment2.1 Cài đặt virtualenv 2.2 Tạo môi trường ảovirtualenv. 2.1 Cài đặt virtualenvvirtualenv2.2 Tạo môi trường ảo 2.2 Tạo môi trường ảo2.3 Khởi động 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 ảo2.4 Tắt môi trường ảo 2.5 Xuất các package đã cài đặt(python_env) 2.4 Tắt môi trường ảo2.5 Xuất các package đã cài đặt 2.5 Xuất các package đã cài đặt2.6 Nhập các package
2.6 Nhập các packageVirtual 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ó 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: Tiếp đến chúng ta sử dụng lệnh 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ố Đã thay đổi trong phiên bản 3.6: Đã thêm tham số Xem PEP 405 để biết thêm thông tin về môi trường ảo Python.PEP 405 for more information about Python virtual environments. Tạo môi trường ảoTạo các môi trường ảo được thực hiện bằng cách thực thi lệnh c:\>c:\Python35\python -m venv c:\path\to\myenv3:virtual environments is done by executing the command c:\>c:\Python35\python -m venv c:\path\to\myenv3: python3 -m venv /path/to/new/virtual/environment Chạy lệnh này tạo thư mục đích (tạo bất kỳ thư mục mẹ nào chưa tồn tại) và đặt tệp c:\>c:\Python35\python -m venv c:\path\to\myenv5 trong đó với khóa c:\>c:\Python35\python -m venv c:\path\to\myenv6 trỏ đến cài đặt Python mà từ đó lệnh được chạy (một tên chung cho thư mục đích là c:\>c:\Python35\python -m venv c:\path\to\myenv7). Nó cũng tạo ra một thư mục con c:\>c:\Python35\python -m venv c:\path\to\myenv8 (hoặc c:\>c:\Python35\python -m venv c:\path\to\myenv9 trên Windows) chứa một bản sao/liên kết của các nhị phân/nhị phân Python (phù hợp với nền tảng hoặc đối số được sử dụng tại thời gian tạo môi trường). Nó cũng tạo ra một thư mục con (ban đầu trống) c:\>python -m venv c:\path\to\myenv0 (trên Windows, đây là c:\>python -m venv c:\path\to\myenv1). Nếu một thư mục hiện có được chỉ định, nó sẽ được sử dụng lại. Đã không dùng nữa vì phiên bản 3.6: c:\>python -m venv c:\path\to\myenv2 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\myenv3 is now recommended for creating virtual environments. Trên Windows, gọi lệnh c:\>c:\Python35\python -m venv c:\path\to\myenv3 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\myenv5 và c:\>python -m venv c:\path\to\myenv6 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 c:\>python -m venv c:\path\to\myenv7, 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 c:\>python -m venv c:\path\to\myenv8 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 c:\>python -m venv c:\path\to\myenv9 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.0 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.1 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.2 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.3 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.3 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 kích hoạ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.4 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\myenv5 đượ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.6, được đặt thà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 nếu c:\>c:\Python35\python -m venv c:\path\to\myenv3 được chạy với 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.9, 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 khác. Trừ khi tùy chọn c:\>python -m venv c:\path\to\myenv9 đượ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)2 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)3 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\myenv3, 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.
PS C: \> \ Scripts \ Activate.ps1 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 environment variable is set to the path of the virtual environment. This can be used to check if one is running inside a virtual environment. Khi môi trường ảo đang hoạt động, biến môi trường 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 được đặt thành đường dẫn của môi trường ảo. Điều này có thể được sử dụng để kiểm tra xem một người đang chạy bên trong môi trường ảo. Bạn không cần phải kích hoạt một môi trường; Kích hoạt chỉ cần chuẩn bị cho môi trường ảo Thư mục nhị phân vào đường dẫn của bạn, do đó, Py Python, gọi trình thông dịch môi trường ảo Python Python và bạn có thể chạy các tập lệnh đã cài đặt mà không phải sử dụng đường dẫn đầy đủ của chúng. Tuy nhiên, tất cả các tập lệnh được cài đặt trong môi trường ảo nên được chạy mà không cần kích hoạt và chạy với môi trường ảo Python Python tự động. Bạn có thể hủy kích hoạt một môi trường ảo bằng cách gõ một cách vô hiệu hóa trên vỏ của bạn. Cơ chế chính xác là đặc trưng cho nền tảng và là một chi tiết triển khai nội bộ (thường là chức năng tập lệnh hoặc shell sẽ được sử dụng). 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 and 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)7 activation scripts. Mới trong phiên bản 3.4: 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.3 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 kích hoạ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.4 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: Các công cụ cài đặt phổ biến như setuptools và pip hoạt động như mong đợi với môi trường ảo. Nói cách khác, khi một môi trường ảo đang hoạt động, họ cài đặt các gói Python vào môi trường ảo mà không cần phải được yêu cầu làm như vậy một cách rõ ràng. Khi một môi trường ảo đang hoạt động (nghĩa là, trình thông dịch python của môi trường ảo đang chạy), các thuộc tí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)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 thư mục cơ sở 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 = '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)0 và 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)1 chỉ vào môi trường không phải Tạo môi trường ảo. Nếu một môi trường ảo không hoạt động, thì 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 giống như 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)0 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 giống như 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)1 (tất cả đều chỉ ra một môi trường không phải là người Virtual Cài đặt Python). Khi môi trường ảo đang hoạt động, mọi tùy chọn thay đổi đường dẫn cài đặt sẽ bị bỏ qua từ tất cả các tệp cấu hình 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)6 để ngăn các dự án được cài đặt vô tình bên ngoài môi trường ảo. Khi làm việc trong shell lệnh, người dùng có thể tạo một môi trường ảo hoạt động bằng cách chạy tập lệnh 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)7 trong thư mục thực thi của môi trường ảo (tên tệp và lệnh chính xác để sử dụng tệp phụ thuộc vào shell), chuẩn bị thư mục của môi trường ảo để thực thi Biến môi trường c:\>python -m venv c:\path\to\myenv5 cho shell chạy. Không cần thiết trong các trường hợp khác để kích hoạt môi trường ảo; Các tập lệnh được cài đặt vào các môi trường ảo có một dòng Shebang Shebang, chỉ vào môi trường ảo. Điều này có nghĩa là tập lệnh sẽ chạy với trình thông dịch đó bất kể giá trị của c:\>python -m venv c:\path\to\myenv5. Trên Windows, xử lý dòng Shebang Shebang được hỗ trợ nếu bạn có trình khởi chạy Python cho Windows được cài đặt (điều này đã được thêm vào Python trong 3.3 - xem PEP 397 để biết thêm chi tiết). Do đó, nhấp đúp vào một tập lệnh được cài đặt trong cửa sổ Windows Explorer sẽ chạy tập lệnh với trình thông dịch chính xác mà không cần phải có bất kỳ tham chiếu nào đến môi trường ảo của nó trong c:\>python -m venv c:\path\to\myenv5.PEP 397 for more details). Thus, double-clicking an installed script in a Windows Explorer window should run the script with the correct interpreter without there needing to be any reference to its virtual environment in c:\>python -m venv c:\path\to\myenv5. Api¶Phương pháp cấp cao được mô tả ở trên sử dụng API đơn giản cung cấp các cơ chế cho người tạo môi trường ảo của bên thứ ba để tùy chỉnh tạo môi trường theo nhu cầu của họ, lớp Lớp
Đã thay đổi trong phiên bản 3.4: Đã thêm tham số Mới trong phiên bản 3.6: Đã thêm tham số Mới trong phiên bản 3.9: Đã thêm tham số Người tạo ra các công cụ môi trường ảo của bên thứ ba sẽ được tự do sử dụng lớp Env-Builder được trả lại là một đối tượng có phương thức, Tạo một môi trường ảo bằng cách chỉ định thư mục đích (tuyệt đối hoặc liên quan đến thư mục hiện tại) là chứa môi trường ảo. Phương pháp Phương pháp 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) Mỗi phương thức Tạo thư mục môi trường và tất cả các thư mục cần thiết, và trả về một đối tượng ngữ cảnh. Đây chỉ là một người giữ cho các thuộc tính (như đường dẫn), để sử dụng bởi các phương thức khác. Các thư mục được phép tồn tại, miễn là Tạo tệp cấu hình c:\>c:\Python35\python -m venv c:\path\to\myenv5 trong môi trường. ________ 97 (Bối cảnh) ¶(context)¶ Tạo một bản sao hoặc Symlink cho Python thực thi trong môi trường. Trên các hệ thống POSIX, nếu một c:\>c:\Python35\python -m venv c:\path\to\myenv00 sẽ được tạo chỉ vào việc thực thi đó, trừ khi các tệp có tên đó đã tồn tại. ________ 101 (bối cảnh) ¶(context)¶ Cài đặt các tập lệnh kích hoạt phù hợp với nền tảng vào môi trường ảo. ________ 102 (Bối cảnh) ¶(context)¶Nâng cấp các gói phụ thuộc VEN Core (hiện tại 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 và c:\>c:\Python35\python -m venv c:\path\to\myenv04) trong môi trường. Điều này được thực hiện bằng cách bắn 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)3 có thể thực thi trong môi trường. Mới trong phiên bản 3.9. ________ 106 (Bối cảnh) ¶(context)¶Một phương thức giữ chỗ có thể được ghi đè trong các triển khai của bên thứ ba để cài đặt sẵn các gói trong môi trường ảo hoặc thực hiện các bước sau sáng tạo khác. Đã thay đổi trong phiên bản 3.7.2: Windows hiện sử dụng các tập lệnh chuyển hướng cho c:\>c:\Python35\python -m venv c:\path\to\myenv07 instead of copying the actual binaries. In 3.7.2 only source 9 does nothing unless running from a build in the source tree.Đã thay đổi trong phiên bản 3.7.3: Windows sao chép các tập lệnh chuyển hướng như một phần của Ngoài ra, Đường dẫn là đường dẫn đến một thư mục nên chứa các thư mục con phổ biến, thì Poss, thì, NT NT, mỗi tập lệnh có các tập lệnh dành cho thư mục bin trong môi trường. Nội dung của Common Common và thư mục tương ứng với c:\>c:\Python35\python -m venv c:\path\to\myenv15 được sao chép sau khi một số văn bản thay thế người giữ chỗ:
Các thư mục được phép tồn tại (vì khi một môi trường hiện tại đang được nâng cấp). Ngoài ra còn có chức năng tiện lợi cấp độ mô-đun: ________ 62 ________ 83 (env_dir, system_site_packages = false(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None, upgrade_deps=False)¶Tạo một c:\>c:\Python35\python -m venv c:\path\to\myenv26 của nó với đối số env_dir. Mới trong phiên bản 3.3. Đã thay đổi trong phiên bản 3.4: Đã thêm tham số Đã thay đổi trong phiên bản 3.6: Đã thêm tham số Đã thay đổi trong phiên bản 3.9: Đã thêm tham số Một ví dụ về việc mở rộng ____ ____ 61¶Tập lệnh sau đây cho thấy cách mở rộng 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) Kịch bản này cũng có sẵn để tải xuống trực tuyến. |