virtualenv -- python虚拟沙盒

 

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

无论认不认同,至少要先认识一下,pip如今却是常常用到,virtualenv第一次据说,不过,总得尝试一下吧。python

 virtualenv 能够将环境和系统环境隔离开,下降耦合linux

1、安装测试

pip install virtualenv

由于我已经安装了pip,那么就直接用pip来安装了,简单方便。网站

其它的安装方式请参考官方网站:http://www.virtualenv.org/en/latest/index.htmlspa

2、建立虚拟环境code

root@kali:/recall/code# virtualenv test_env
New python executable in test_env/bin/python
Installing setuptools, pip...done.
root@kali:/recall/code# 

很简单,就是virtualenv 环境名称[自定义的名称,本身喜欢什么就写什么]orm

默认状况下,虚拟环境会依赖系统环境中的site packages,就是说系统中已经安装好的第三方package也会安装在虚拟环境中,htm

若是不想依赖这些package,那么能够加上参数 blog

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

3、启动虚拟环境

建立成功后,会在当前目录下生成对应的目录文件。

复制代码
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# 
复制代码
相关文章
相关标签/搜索