有人說:virtualenv、fabric 和 pip 是 pythoneer 的三大神器。
不管認不認同,至少要先認識一下,pip現在倒是經常用到,virtualenv第一次聽說,不過,總得嘗試一下吧。
一、安裝
pip install virtualenv
因為我已經安裝了pip,那么就直接用pip來安裝了,簡單方便。
其它的安裝方式請參考官方網站:http://www.virtualenv.org/en/latest/index.html
二、創建虛擬環境
root@kali:/recall/code# virtualenv test_env New python executable in test_env/bin/python Installing setuptools, pip...done. root@kali:/recall/code#
很簡單,就是virtualenv 環境名稱[自定義的名稱,自己喜歡什么就寫什么]
默認情況下,虛擬環境會依賴系統環境中的site packages,就是說系統中已經安裝好的第三方package也會安裝在虛擬環境中,
如果不想依賴這些package,那么可以加上參數
--no-site-packages
建立虛擬環境
即變成了:
root@kali:/recall/code# virtualenv test_env --no-site-packages New python executable in test_env/bin/python Installing setuptools, pip...done. root@kali:/recall/code#
三、啟動虛擬環境
創建成功后,會在當前目錄下生成對應的目錄文件。
root@kali:/recall/code# ls -l test_env/ 總用量 16 drwxr-xr-x 2 root root 4096 4月 29 20:03 bin drwxr-xr-x 2 root root 4096 4月 29 19:58 include drwxr-xr-x 3 root root 4096 4月 29 19:58 lib drwxr-xr-x 2 root root 4096 4月 29 19:58 local root@kali:/recall/code#
我們先進入到該目錄下:
cd test_env/
然后啟動
root@kali:/recall/code/test_env# source ./bin/activate
啟動成功后,會在前面多出 test_env 字樣,如下所示
(test_env)root@kali:/recall/code/test_env#
四、使用測試
(test_env)root@kali:/recall/code/test_env# pip install requests Downloading/unpacking requests Downloading requests-2.2.1-py2.py3-none-any.whl (625kB): 625kB downloaded Installing collected packages: requests Successfully installed requests Cleaning up... (test_env)root@kali:/recall/code/test_env# python Python 2.7.3 (default, Jan 2 2013, 13:56:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> >>> response = requests.get("http://www.baidu.com") >>> response.status_code 200 >>>
五、退出虛擬環境
deactivate
完整如下:
(test_env)root@kali:/recall/code/test_env# python Python 2.7.3 (default, Jan 2 2013, 13:56:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> >>> response = requests.get("http://www.baidu.com") >>> response.status_code 200 >>> exit() (test_env)root@kali:/recall/code/test_env# deactivate root@kali:/recall/code/test_env#
更多資料請百度、google 或查看官方文檔。