用virtualenv建立多個Python獨立開發環境

整理自: http://www.nowamagic.net/academy/detail/1330228

什麼是virtualenv?

在Python的開發環境的最常用的方法是使用 virtualenv 包。 Virtualenv是一個用來創建獨立的Python環境的包。現在,出現了這樣的問題:爲什麼我們需要一個獨立的Python環境? 要回答這個問題,請允許我引用virtualenv自己的文檔:

virtualenv is a tool to create isolated Python environments.

The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

我們需要處理的基本問題是包的依賴、版本和間接權限問題。想象一下,你有兩個應用,一個應用需要libfoo的版本1,而另一應用需要版本2。如何才能同時使用這些應用程序?如果您安裝到的/usr/lib/python2.7/site-packages(或任何平臺的標準位置)的一切,在這種情況下,您可能會不小心升級不應該升級的應用程序。

簡單地說,你可以爲每個項目建立不同的/獨立的Python環境,你將爲每個項目安裝所有需要的軟件包到它們各自獨立的環境中。

安裝與使用virtualenv

安裝 virtualenv 很簡單:

1 pip installvirtualenv

virtualenv安裝完畢後,可以通過運行下面的命令來爲你的項目創建獨立的python環境:

1 mkdir nowamagic_venv
2 virtualenv --distribute nowamagic_venv

OK,成功。上面發生了什麼?你創建了文件夾 nowamagic_venv 來存儲你的新的獨立Python環境。 這個文件夾位於 /root 下面。

我們再來看看輸出:

1 New python executable innowamagic_venv/bin/python2.7
2 Also creating executable innowamagic_venv/bin/python
3 Installing Setuptools......done.
4 Installing Pip...........done.

--distribute 選項使virtualenv使用新的基於發行版的包管理系統而不是 setuptools 獲得的包。 你現在需要知道的就是 --distribute 選項會自動在新的虛擬環境中安裝 pip ,這樣就不需要手動安裝了。 當你成爲一個更有經驗的Python開發者,你就會明白其中細節。



發佈了43 篇原創文章 · 獲贊 12 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章