注释
在使用virtualenv前ubuntu默认的解释器是python2.7,而且/usr/lib/python3里面已经安装好了ipython3和requests
$ python
python 2.7.12 (default, nov 19 2016, 06:48:10)
[gcc 5.4.0 20160609] on linux2
type “help”, “copyright”, “credits” or “license” for more information.
>>>$ ipython3
python 3.5.2 (default, nov 17 2016, 17:05:23)
type “copyright”, “credits” or “license” for more information.
ipython 5.1.0 — an enhanced interactive python.
? -> introduction and overview of ipython’s features.
%quickref -> quick reference.
help -> python’s own help system.
object? -> details about ‘object’, use ‘object??’ for extra details.
in [1]: import requests
in [2]:使用
由于一些兼容性问题,电脑上默认的python版本只能只能使用python2.7,所以创建命令要另外使用-p指定解释器
$ mkdir my_project_folder; cd my_project_folder
# 创建虚拟环境
$ virtualenv -p /usr/bin/python3 venv
running virtualenv with interpreter /usr/bin/python3
using base prefix ‘/usr’
new python executable in /home/ormsf/my_project_folder/venv/bin/python3
also creating executable in /home/ormsf/my_project_folder/venv/bin/python
installing setuptools, pkg_resources, pip, wheel…done.
激活虚拟环境
$ source venv/bin/activate
现在可以看到提示符前面多了一个venv,代表虚拟环境创建成功
(venv) ~/my_project_folder $ ipython3
实践一下,虚拟环境和实际的环境隔离的
# 无法使用ipython3
(venv) ~/my_project_folder $ ipython3
traceback (most recent call last):
file “/usr/bin/ipython3”, line 4, in
from ipython import start_ipython
importerror: no module named ‘ipython’
# 默认的解释器已经变成了python3
(venv) ~/my_project_folder $ python
python 3.5.2 (default, nov 17 2016, 17:05:23)
[gcc 5.4.0 20160609] on linux
type “help”, “copyright”, “credits” or “license” for more information.
# 无法使用requests
>>> import requests
traceback (most recent call last):
file “”, line 1, in
importerror: no module named ‘requests’
注意不需要使用pip3
(venv) ~/my_project_folder $ pip install requests
collecting requests
downloading requests-2.13.0-py2.py3-none-any.whl (584kb)
100% |████████████████████████████████| 593kb 1.3mb/s
installing collected packages: requests
successfully installed requests-2.13.0
现在request已经能够正确使用了
(venv) ~/my_project_folder $ python
python 3.5.2 (default, nov 17 2016, 17:05:23)
[gcc 5.4.0 20160609] on linux
type “help”, “copyright”, “credits” or “license” for more information.
>>> import requests
>>>(venv) ~/my_project_folder $ pip install ipython
现在ipython也已经能够正确使用了
(venv) ~/my_project_folder $ ipython
python 3.5.2 (default, nov 17 2016, 17:05:23)
type “copyright”, “credits” or “license” for more information.
ipython 5.1.0 — an enhanced interactive python.
? -> introduction and overview of ipython’s features.
%quickref -> quick reference.
help -> python’s own help system.
object? -> details about ‘object’, use ‘object??’ for extra details.
in [1]:
退出
(venv) ~/my_project_folder $ deactivate
原理很简单,就是把系统python复制一份到virtualenv的环境,用命令source venv/bin/activate进入一个virtualenv环境时,virtualenv会修改相关环境变量,让命令python和pip均指向当前的virtualenv环境。
更多python-virtualenv 相关文章请关注php中文网!