12. 虛擬環境與套件

12.1. 簡介

Python 應用程式通常會用到不在標準函式庫的套件和模組。應用程式有時候會需要某個特定版本的函式庫,因為這個應用程式可能需要某個特殊的臭蟲修正,或是這個應用程式是根據該函式庫特定版本的介面所撰寫。

這意味著不太可能安裝一套 Python 就可以滿足所有應用程式的要求。如果應用程式 A 需要一個特定的模組的 1.0 版,但另外一個應用程式 B 需要 2.0 版,那麼這整個需求不管安裝 1.0 或是 2.0 都會衝突,以致於應用程式無法使用。

The solution for this problem is to create a virtual environment (often shortened to 「virtualenv」), a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.

Different applications can then use different virtual environments. To resolve the earlier example of conflicting requirements, application A can have its own virtual environment with version 1.0 installed while application B has another virtualenv with version 2.0. If application B requires a library be upgraded to version 3.0, this will not affect application A’s environment.

12.2. 建立虛擬環境

The script used to create and manage virtual environments is called pyvenv. pyvenv will usually install the most recent version of Python that you have available; the script is also installed with a version number, so if you have multiple versions of Python on your system you can select a specific Python version by running pyvenv-3.4 or whichever version you want.

To create a virtualenv, decide upon a directory where you want to place it and run pyvenv with the directory path:

pyvenv tutorial-env

如果 tutorial-env 不存在的話,這會建立 tutorial-env 資料夾,並且也會在裡面建立一個有 Python 直譯器的複本、標準函式庫、以及不同的支援檔案的資料夾。

Once you’ve created a virtual environment, you need to activate it.

在 Windows 系統中,使用:

tutorial-env/Scripts/activate

在 Unix 或 MacOS 系統,使用:

source tutorial-env/bin/activate

(這段程式碼適用於 bash shell。如果你是用 csh 或者 fish shell,應當使用替代的 activate.cshactivate.fish 腳本。)

Activating the virtualenv will change your shell’s prompt to show what virtualenv you’re using, and modify the environment so that running python will get you that particular version and installation of Python. For example:

-> source ~/envs/tutorial-env/bin/activate
(tutorial-env) -> python
Python 3.4.3+ (3.4:c7b9645a6f35+, May 22 2015, 09:31:25)
  ...
>>> import sys
>>> sys.path
['', '/usr/local/lib/python34.zip', ...,
'~/envs/tutorial-env/lib/python3.4/site-packages']
>>>

12.3. 用 pip 管理套件

Once you’ve activated a virtual environment, you can install, upgrade, and remove packages using a program called pip. By default pip will install packages from the Python Package Index, <https://pypi.python.org/pypi>. You can browse the Python Package Index by going to it in your web browser, or you can use pip’s limited search feature:

(tutorial-env) -> pip search astronomy
skyfield               - Elegant astronomy for Python
gary                   - Galactic astronomy and gravitational dynamics.
novas                  - The United States Naval Observatory NOVAS astronomy library
astroobs               - Provides astronomy ephemeris to plan telescope observations
PyAstronomy            - A collection of astronomy related tools for Python.
...

pip 有好幾個子指令:」search」、」install」、」uninstall」、」freeze」 等等。(這可以參考安裝 Python 模組說明書來取得 pip 的完整文件說明。)

You can install the latest version of a package by specifying a package’s name:

-> pip install novas
Collecting novas
  Downloading novas-3.1.1.3.tar.gz (136kB)
Installing collected packages: novas
  Running setup.py install for novas
Successfully installed novas-3.1.1.3

You can also install a specific version of a package by giving the package name followed by == and the version number:

-> pip install requests==2.6.0
Collecting requests==2.6.0
  Using cached requests-2.6.0-py2.py3-none-any.whl
Installing collected packages: requests
Successfully installed requests-2.6.0

If you re-run this command, pip will notice that the requested version is already installed and do nothing. You can supply a different version number to get that version, or you can run pip install --upgrade to upgrade the package to the latest version:

-> pip install --upgrade requests
Collecting requests
Installing collected packages: requests
  Found existing installation: requests 2.6.0
    Uninstalling requests-2.6.0:
      Successfully uninstalled requests-2.6.0
Successfully installed requests-2.7.0

pip uninstall 後面接一個或是多個套件名稱可以從虛擬環境中移除套件。

pip show will display information about a particular package:

(tutorial-env) -> pip show requests
---
Metadata-Version: 2.0
Name: requests
Version: 2.7.0
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@kennethreitz.com
License: Apache 2.0
Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages
Requires:

pip list will display all of the packages installed in the virtual environment:

(tutorial-env) -> pip list
novas (3.1.1.3)
numpy (1.9.2)
pip (7.0.3)
requests (2.7.0)
setuptools (16.0)

pip freeze will produce a similar list of the installed packages, but the output uses the format that pip install expects. A common convention is to put this list in a requirements.txt file:

(tutorial-env) -> pip freeze > requirements.txt
(tutorial-env) -> cat requirements.txt
novas==3.1.1.3
numpy==1.9.2
requests==2.7.0

The requirements.txt can then be committed to version control and shipped as part of an application. Users can then install all the necessary packages with install -r:

-> pip install -r requirements.txt
Collecting novas==3.1.1.3 (from -r requirements.txt (line 1))
  ...
Collecting numpy==1.9.2 (from -r requirements.txt (line 2))
  ...
Collecting requests==2.7.0 (from -r requirements.txt (line 3))
  ...
Installing collected packages: novas, numpy, requests
  Running setup.py install for novas
Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0

pip 還有更多功能。可以參考安裝 Python 模組說明書來取得完整的 pip 參考資料。當你撰寫了一個套件並且想要讓它可以在 Python Package Index 上可以取得的話,可以參考發布 Python 模組說明。