W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
You want to create a new Python environment in which you can install modules andpackages. However, you want to do this without installing a new copy of Python ormaking changes that might affect the system Python installation.
You can make a new “virtual” environment using the pyvenv command. This commandis installed in the same directory as the Python interpreter or possibly in the Scriptsdirectory on Windows. Here is an example:
bash % pyvenv Spam
bash %
The name supplied to pyvenv is the name of a directory that will be created. Uponcreation, the Spam directory will look something like this:
bash % cd Spam
bash % ls
bin include lib pyvenv.cfg
bash %
In the bin directory, you’ll find a Python interpreter that you can use. For example:
bash % Spam/bin/python3
Python 3.3.0 (default, Oct 6 2012, 15:45:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from pprint import pprint
>>> import sys
>>> pprint(sys.path)
['',
'/usr/local/lib/python33.zip',
'/usr/local/lib/python3.3',
'/usr/local/lib/python3.3/plat-darwin',
'/usr/local/lib/python3.3/lib-dynload',
'/Users/beazley/Spam/lib/python3.3/site-packages']
>>>
A key feature of this interpreter is that its site-packages directory has been set to thenewly created environment. Should you decide to install third-party packages, they willbe installed here, not in the normal system site-packages directory.
The creation of a virtual environment mostly pertains to the installation and managementof third-party packages. As you can see in the example, the sys.path variablecontains directories from the normal system Python, but the site-packages directory hasbeen relocated to a new directory.
With a new virtual environment, the next step is often to install a package manager,such as distribute or pip. When installing such tools and subsequent packages, youjust need to make sure you use the interpreter that’s part of the virtual environment.This should install the packages into the newly created site-packages directory.
Although a virtual environment might look like a copy of the Python installation, itreally only consists of a few files and symbolic links. All of the standard library files andinterpreter executables come from the original Python installation. Thus, creating suchenvironments is easy, and takes almost no machine resources.
By default, virtual environments are completely clean and contain no third-party addons.If you would like to include already installed packages as part of a virtual environment,create the environment using the –system-site-packages option. For example:
bash % pyvenv --system-site-packages Spam
bash %
More information about pyvenv and virtual environments can be found inPEP 405 .
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: