對于Python開發新手,很多人會迷茫那些各種名目的工具和概念,如Python2.7, Python3.3, Distribute, pip, virtualenv,Setuptools, easy_install, 這些東東到底幹嘛的,有什麼作用,為什麼每個配置教程總會碰到它們,到底該如何選擇?好吧,不必都搞懂,隻要知道目前怎麼配置最合适就行了。本文記錄了最新的Python虛拟環境配置流程,個人覺得也是最優雅幹淨的配置方式,如果還在用一些亂糟糟的方法配置,還是棄暗投明吧。
環境:Win8.1, Python2.7, Python3.3, Distribute, pip, virtualenv, virtualenvwrapper-powershell, PowerShell.
歡迎轉載或參考,但請尊重作者勞動成果,轉載請注明出處,參考請引用連結!
目錄
- 概念
- Distribute -> Setuptools
- pip -> easy_install
- virtualenv
- 配置
- 運作powershell
- 安裝Python
- 安裝Distribute
- 安裝Pip
- 安裝virtualenv和virtualenvwrapper-powershell
- 修複中文字尾BUG
- 使用virtualenv
- 最後
概念
初學Pyhon,恐怕絕大部分人都會面對Distribute, Setuptools, pip, easy_install, virtualenv等工具吧,這些東西到底是什麼呢?http://guide.python-distribute.org/index.html 給出了前四個的解釋,以及所有工具的配置教程。
Distribute -> Setuptools
Distribute is a collection of enhancements to the Python standard library module: distutils (for Python 2.3.5 and up on most platforms; 64-bit platforms require a minimum of Python 2.4) that allows you to more easily build and distribute Python packages, especially ones that have dependencies on other packages.
Distribute was created because the Setuptools package is no longer maintained. Third-party packages will likely require setuptools, which is provided by the Distribute package. Therefore, anytime time a packages depends on the Setuptools package, Distribute will step in to say it already provides the setuptools module.
Distribute是Setuptools的替代方案。它們都是Python标準庫子產品的增強,可以讓人們很友善地建立和釋出Python包,特别是在有依賴的情況下。既然Distribute是Setuptools的替代方案,能用Distribute就别用Setuptools了。
pip -> easy_install
Pip is an installer for Python packages written by Ian Bicking. It can install packages, list installed packages, upgrade packages and uninstall packages.
The pip application is a replacement for easy_install. It uses mostly the same techniques for finding packages, so packages that were made easy_installable should be pip-installable as well.
pip是easy_install的替代方案。它們都是Python包管理工具,可以讓人們很友善地安裝,更新,解除安裝Python包。既然pip是easy_install的替代方案,能用pip就别用easy_install了。
virtualenv
http://www.tylerbutler.com/2012/05/how-to-install-python-pip-and-virtualenv-on-windows-with-powershell/ 給出了一些說明:
The more Python development you do, though, the more packages you’re going to need. Wouldn’t it be nice if you could install all the packages into a ‘special’ location where they wouldn’t interfere with any other packages? This is where virtualenv comes in. It creates a virtual Python interpreter and isolates any packages installed for that interpreter from others on the system. There are lots of ways this comes in handy; I’ll leave enumerating them as an exercise for the reader, but if you think for a minute you can see why this will come in handy. And if you can’t yet, then give yourself a few weeks of Python development, then come back and look at this post again once you realize you need to use virtualenv.
對于開發者來說,Python的包各種各樣,版本也各種各樣,如果所有的包都裝在一個Python環境裡面,難免會遇到一些沖突情況,而且部署在其他地方的時候也顯得臃腫備援。virtualenv是這樣一個工具,可以虛拟出N個獨立的Python的工作環境,針對某一個應用所需要的包,都裝在某一個特定的虛拟環境裡面,不同的環境互不幹擾。使用虛拟環境來管理自己的應用所需要的包,是非常優雅的事。當然你隻是随便用用,都裝置一個Python環境裡面也無可厚非。
配置
本文記錄了Windows 8.1下面搭建Python虛拟環境的操作流程。
運作powershell
PowerShell是Windows的shell工具,提供類似UNIX系統裡面的一些指令。Windows 7和Windows 8預設自帶PowerShell,如果是Windows XP之類的,可能還要自己先裝下PowerShell。
Win + R 打開啟動對話框,輸入 powershell 啟動PowerShell工具。
Tip
在PowerShell中滑鼠選中文字,右鍵則表示複制;滑鼠移動到光标處,右鍵則表示粘貼。
安裝Python
從Python官網(http://python.org/download/)下載下傳Python 2.x和Python 3.x的32bit Windows Installer。
本例中下載下傳的是 python-2.7.6.exe 和 python-3.3.3.exe ,分别安裝在 D:/Python/Python27 和 D:/Python/Python33 路徑下,預設沒有将Python路徑配置進系統環境變量内。
在系統變量中建立一項,變量名為 Python,變量值為 D:/Python/Python27 (以Python2.7為例,需要使用Python3.3時将Python 變量修改為 D:/Python/Python33 即可)。編輯 Path 變量,在末尾添加 ;%Python%;%Python%/Scripts。
重新打開PowerShell,輸入指令 python, 如果顯示如下,則表示配置成功。
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>
安裝Distribute
将 distribute_setup.py 下載下傳到 D:/Python/ 目錄下。
打開PowerShell,運作指令 python D:/Python/distribute_setup.py 即可完成安裝。
安裝Pip
将 get-pip.py 下載下傳到 D:/Python/ 目錄下。
打開PowerShell,運作指令 python D:/Python/get-pip.py 即可完成安裝。
如果不需要配置Python虛拟環境,則到這一步就可以結束了。
安裝virtualenv和virtualenvwrapper-powershell
在安裝前有兩件事情要做:第一是確定PowerShell的執行政策允許執行 import-module 指令,否則會出現政策錯誤提示,修改組政策需要以管理者身份運作PowerShell;第二是要設定使用者的 WORKON_HOME 環境變量,也可以不設定,預設為系統的使用者目錄 "C:/Users/xxxx"。
- 打開PowerShell,輸入 Start-Process powershell -Verb runas 将會以管理者身份打開另外一個PowerShell,在新打開的PowerShell裡面輸入 Set-ExecutionPolicy RemoteSigned 會顯示如下資訊,回車即可完成政策修改:
執行政策更改 執行政策可幫助你防止執行不信任的腳本。更改執行政策可能會産生安全風險,如http://go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies 幫助主題所述。是否要更改執行政策? [Y] 是(Y) [N] 否(N) [S] 挂起(S) [?] 幫助 (預設值為“Y”):
- 打開使用者環境變量設定視窗,在使用者變量裡建立 WORKON_HOME 變量,值設定為 D:/Python/Envs,如下圖:
Tip
在PowerShell裡面使用 $env:WORKON_HOME="D:/Python/Envs" 可以臨時設定 WORKON_HOME 變量,設定後關閉PowerShell即失效。
運作下面的指令,完成virtualenv和irtualenvwrapper-powershell的安裝設定:
pip install virtualenv
pip install virtualenvwrapper-powershell
mkdir $env:WORKON_HOME
cd $env:WORKON_HOME
import-module virtualenvwrapper
前兩條指令使用pip安裝virtualenv和virtualenvwrapper-powershell;第3條指令建立 WORKON_HOME 變量指向的檔案夾,如果出現錯誤,可能是變量沒有生效,重新開機powershell或者重新開機計算機;最後兩條指令則是在PowerShell中導入virtualenvwrapper子產品。
完成上面的設定後,在PowerShell中輸入指令 Get-Command *virtualenv* 就能夠看到virtualenv的快捷指令了:
PS C:\Users\XPS 12> Get-Command *virtualenv*
CommandType Name ModuleName
----------- ---- ----------
Alias cdvirtualenv -> VirtualEnvWrapper
Alias cpvirtualenv -> VirtualEnvWrapper
Alias lsvirtualenv -> VirtualEnvWrapper
Alias mkvirtualenv -> VirtualEnvWrapper
Alias rmvirtualenv -> VirtualEnvWrapper
Function add2virtualenv VirtualEnvWrapper
Function CDIntoVirtualEnvironment VirtualEnvWrapper
Function Copy-VirtualEnvironment VirtualEnvWrapper
Function GetVirtualEnvData VirtualEnvWrapper
Function Get-VirtualEnvironment VirtualEnvWrapper
Function LooksLikeAVirtualEnv VirtualEnvWrapper
Function NewVirtualEnvData VirtualEnvWrapper
Function New-VirtualEnvironment VirtualEnvWrapper
Function Remove-VirtualEnvironment VirtualEnvWrapper
Function Set-VirtualEnvironment VirtualEnvWrapper
Function showvirtualenv VirtualEnvWrapper
Function virtualenvwrapper_get_python_version VirtualEnvWrapper
Function virtualenvwrapper_get_site_packages_dir VirtualEnvWrapper
Application virtualenv.exe
Application virtualenv-2.7.exe
常用的就是那幾個有别名的指令了,lsvirtualenv -> 列出環境,mkvirtualenv -> 建立環境,rmvirtualenv -> 删除環境(通常需要帶 -r 參數疊代删除)。
修複中文字尾BUG
打開PowerShell,輸入指令 mkvirtualenv testenv --no-site-packages 建立名為 testenv 的Python環境。如果安裝有阿裡旺旺,則可能會出現下面的一系列錯誤資訊:
PS C:\Users\XPS 12> mkvirtualenv testenv --no-site-packages
New python executable in testenv\Scripts\python.exe
Installing setuptools, pip...
Complete output from command D:\Python\Envs\testenv\Scripts\python.exe -c "import sys, pip; sys...d\"] + sys.argv[1:])
)" setuptools pip:
Ignoring indexes: https://pypi.python.org/simple/
Downloading/unpacking setuptools
Cleaning up...
Exception:
Traceback (most recent call last):
File "D:\Python\Python27\lib\site-packages\virtualenv_support\pip-1.5.1-py2.py3-none-any.whl\pip\basecommand.py", line
122, in main
status = self.run(options, args)
File "D:\Python\Python27\lib\site-packages\virtualenv_support\pip-1.5.1-py2.py3-none-any.whl\pip\commands\install.py",
line 274, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "D:\Python\Python27\lib\site-packages\virtualenv_support\pip-1.5.1-py2.py3-none-any.whl\pip\req.py", line 1166, i
n prepare_files
url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
File "D:\Python\Python27\lib\site-packages\virtualenv_support\pip-1.5.1-py2.py3-none-any.whl\pip\index.py", line 209,
in find_requirement
file_locations, url_locations = self._sort_locations(locations)
File "D:\Python\Python27\lib\site-packages\virtualenv_support\pip-1.5.1-py2.py3-none-any.whl\pip\index.py", line 128,
in _sort_locations
sort_path(os.path.join(path, item))
File "D:\Python\Python27\lib\site-packages\virtualenv_support\pip-1.5.1-py2.py3-none-any.whl\pip\index.py", line 109,
in sort_path
if mimetypes.guess_type(url, strict=False)[0] == \'text/html\':
File "D:\Python\Python27\Lib\mimetypes.py", line 303, in guess_type
init()
File "D:\Python\Python27\Lib\mimetypes.py", line 364, in init
db.read_windows_registry()
File "D:\Python\Python27\Lib\mimetypes.py", line 264, in read_windows_registry
for subkeyname in enum_types(hkcr):
File "D:\Python\Python27\Lib\mimetypes.py", line 249, in enum_types
ctype = ctype.encode(default_encoding) # omit in 3.x!
UnicodeDecodeError: \'ascii\' codec can\'t decode byte 0xb0 in position 1: ordinal not in range(128)
Storing debug log for failure in C:\Users\XPS 12\pip\pip.log
----------------------------------------
...Installing setuptools, pip...done.
Traceback (most recent call last):
File "D:\Python\Python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "D:\Python\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "D:\Python\Python27\Scripts\virtualenv.exe\__main__.py", line 9, in <module>
File "D:\Python\Python27\lib\site-packages\virtualenv.py", line 824, in main
symlink=options.symlink)
File "D:\Python\Python27\lib\site-packages\virtualenv.py", line 992, in create_environment
install_wheel(to_install, py_executable, search_dirs)
File "D:\Python\Python27\lib\site-packages\virtualenv.py", line 960, in install_wheel
\'PIP_NO_INDEX\': \'1\'
File "D:\Python\Python27\lib\site-packages\virtualenv.py", line 902, in call_subprocess
% (cmd_desc, proc.returncode))
OSError: Command D:\Python\Envs\testenv\Scripts\python.exe -c "import sys, pip; sys...d\"] + sys.argv[1:]))" setuptools
pip failed with error code 2
Added activation script por Powershell to D:\Python\Envs/testenv\Scripts.
(testenv)PS C:\Users\XPS 12>
據說這是由“*.阿裡旺旺接收的可疑檔案”引起的漢字編碼問題,解決方案為:打開 D:/Python/Python27/Lib/mimetypes.py 檔案,找到default_encoding = sys.getdefaultencoding() 一行,在前面添加下面的代碼,儲存并退出即可。(Refer: 參考http://webrawler.blog.51cto.com/8343567/1339637 )
# begin fix bug
if sys.getdefaultencoding() != \'gbk\':
reload(sys)
sys.setdefaultencoding(\'gbk\')
# end
Tip
使用 deactivate 指令退出 testenv 環境,使用 rmvirtualenv testenv 指令删除剛才建立的 testenv 環境。
使用virtualenv
在PowerShell下面使用virtualenv,下面的這幾個指令比較常用:
- mkvirtualenv env_name --no-site-packages 可以用來建立新的虛拟環境。參數 --no-site-packages 可以用來阻止指令将原來Python系統中裝過的包複制到新的虛拟環境裡面。
- deactivate 用來退出目前的虛拟環境。
- lsvirtualenv 用來列出所有的虛拟環境。
- workon env_name 用來激活,或者切換到某一個虛拟環境下。
- rmvirtualenv env_name -r 用來删除某一個虛拟環境。參數 -r 表示疊代删除,往往目錄非空的時候得帶上這個參數。
如果需要在其它地方使用virtualenv,則先從PowerShell進入到對應的virtualenv,然後再打開對應的程式。或者參照D:/Python/Envs/env_name/Scripts/activate.bat 檔案的内容配置。對于IDE來說通常配置D:/Python/Envs/env_name/Scripts/python.exe 即可。
最後
個人覺得結構還是很清晰的,針對特定的應用使用特定的virtualenv确實很優雅,一次配置好後使用起來也并不麻煩,但并不是每個人都需要virtualenv。
http://my.phirobot.com/blog/2014-02-python_in_windows.html