virtualenv -- python虛擬沙盒

題記

有人說:virtualenv、fabric 和 pip 是 pythoneer 的三大神器。html

無論認不認同,至少要先認識一下,pip如今卻是常常用到,virtualenv第一次據說,不過,總得嘗試一下吧。python

1、安裝

pip install virtualenv

由於我已經安裝了pip,那麼就直接用pip來安裝了,簡單方便。linux

其它的安裝方式請參考官方網站:http://www.virtualenv.org/en/latest/index.html測試

2、建立虛擬環境

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也會安裝在虛擬環境中,code

若是不想依賴這些package,那麼能夠加上參數orm

--no-site-packages

創建虛擬環境htm

即變成了:教程

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#

3、啓動虛擬環境

建立成功後,會在當前目錄下生成對應的目錄文件。ip

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#

4、使用測試

(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
>>>

5、退出虛擬環境

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#

更多入門教程能夠參考 (http://www.bugingcode.com/python_start/)

相關文章
相關標籤/搜索