python3 virtualenv

2019-05-17  本文已影响0人  Devops海洋的渔夫

在安装了python3之后,在项目开发的过程中,使用pip3进行库安装都会下载安装到环境变量设置好的地方,也就是python3安装的根目录下。
但是如果同时要开发多个不同的应用项目,而不同应用项目对于同一个库需要适配不同的版本,这种情况怎么办呢?

一般解决的方式有多种。
一种是采用docker镜像,一个应用使用一个镜像进行独立环境运行。
另一种则是安装virtualenv,实现环境的隔离,将第三方库下载到特定的隔离路径下即可。

下面,我这里使用Centos7要演示一下。

现在看看默认Centos7安装第三方库之后的存放路径

第一个就是/usr/local/python3/bin目录下。

[root@server01 python3]# ls
bin  include  lib  share
[root@server01 python3]# pwd
/usr/local/python3
[root@server01 python3]# ls bin/
2to3              idle3.7   pip3         python3            pyvenv
2to3-3.7          iptest    pip3.7       python3.7          pyvenv-3.7
django-admin      iptest3   __pycache__  python3.7-config   sqlformat
django-admin.py   ipython   pydoc3       python3.7m
easy_install-3.7  ipython3  pydoc3.7     python3.7m-config
idle3             pip       pygmentize   python3-config
[root@server01 python3]# 

可以看到,这里面有安装好的djangoipython等工具。
下面来看看,安装好了virtualenv之后,我再下载这些第三方库,看看存放的路径。

安装virtualenv

pip3 install virtualenv

[root@server01 python3]# pip3 install virtualenv
Collecting virtualenv
  Downloading https://files.pythonhosted.org/packages/ca/ee/8375c01412abe6ff462ec80970e6bb1c4308724d4366d7519627c98691ab/virtualenv-16.6.0-py2.py3-none-any.whl (2.0MB)
     |████████████████████████████████| 2.0MB 14kB/s 
Installing collected packages: virtualenv
Successfully installed virtualenv-16.6.0
WARNING: You are using pip version 19.1, however version 19.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@server01 python3]# 
[root@server01 python3]# cd bin/
[root@server01 bin]# ls
2to3              idle3.7   pip3         python3            pyvenv
2to3-3.7          iptest    pip3.7       python3.7          pyvenv-3.7
django-admin      iptest3   __pycache__  python3.7-config   sqlformat
django-admin.py   ipython   pydoc3       python3.7m         virtualenv
easy_install-3.7  ipython3  pydoc3.7     python3.7m-config
idle3             pip       pygmentize   python3-config
[root@server01 bin]# ./virtualenv -v
You must provide a DEST_DIR
Usage: virtualenv [OPTIONS] DEST_DIR

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -v, --verbose         Increase verbosity.
  -q, --quiet           Decrease verbosity.
  -p PYTHON_EXE, --python=PYTHON_EXE

可以看到已经安装好了二进制执行文件在python3的bin目录下。

软链接virtualenv到/usr/bin目录

上面虽然已经安装好了,但是如果到其他路径下执行命令,就会如下报错:

[root@server01 ~]# virtualenv -v
-bash: virtualenv: command not found

执行将virtualenv的二进制可执行文件软链接到/usr/bin目录即可。
ln -s /usr/local/python3/bin/virtualenv /usr/bin/virtualenv

执行如下:

[root@server01 ~]# ls /usr/local/python3/bin/virtualenv 
/usr/local/python3/bin/virtualenv
[root@server01 ~]# ln -s /usr/local/python3/bin/virtualenv /usr/bin/virtualenv
[root@server01 ~]# 
[root@server01 ~]# virt
virtualenv  virt-what   
[root@server01 ~]# virtualenv -v
You must provide a DEST_DIR
Usage: virtualenv [OPTIONS] DEST_DIR

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -v, --verbose         Increase verbosity.
  -q, --quiet           Decrease verbosity.

软链接到usr/bin目录之后,就可以在全局目录下执行了。

创建一个python3独立的运行环境

在上面安装好了virtualenv工具之后,下面就可以来创建一个独立安装第三方库的运行环境了。

首先创建一个运行独立环境的项目目录

[root@server01 ~]# mkdir myproject
[root@server01 ~]# cd myproject/
[root@server01 myproject]# ls
[root@server01 myproject]# 

创建这个目录的独立第三方库安装环境,命名为venv

virtualenv --no-site-packages venv

[root@server01 myproject]# virtualenv --no-site-packages venv
Using base prefix '/usr/local/python3'
New python executable in /root/myproject/venv/bin/python3.7
Also creating executable in /root/myproject/venv/bin/python
Installing setuptools, pip, wheel...
done.
[root@server01 myproject]# 

这里使用了--no-site-packages参数,就是不带任何python环境下的第三方库过来。这样就创建了一个纯净的python环境了。

查看新建的venv环境

[root@server01 myproject]# ls
venv
[root@server01 myproject]# ls venv/
bin  include  lib
[root@server01 myproject]# 

可以看到,在当前目录下多了一个venv的目录,这个目录里面有基础的python环境。

那么怎么使用呢?

使用source进入该环境

source venv/bin/activate

[root@server01 myproject]# source venv/bin/activate
(venv) [root@server01 myproject]# 
(venv) [root@server01 myproject]# ls
venv
(venv) [root@server01 myproject]# 

可以看到进入环境之后,命令多了(venv)的前缀。此时,如果再这个环境想要使用ipython3能不能使用呢?

(venv) [root@server01 myproject]# ipython3
/usr/local/python3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:925: UserWarning: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
  warn("Attempting to work in a virtualenv. If you encounter problems, please "
Python 3.7.1 (default, May  2 2019, 14:58:59) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import django                                                            

按照验证来看,这样是不影响使用的。但是其实是跳到了全局环境去操作了,所以import django也没有报错。

如果不使用ipython3,直接使用python3,则会如下:

(venv) [root@server01 myproject]# python3
Python 3.7.1 (default, May  2 2019, 14:58:59) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'django'
>>> 

说明原生的python3并没有使用全局环境的第三方库,如果要使用的话,就要在venv下安装对应的第三方库。

在venv环境下安装django库

(venv) [root@server01 myproject]# pip3 install django
Collecting django
  Using cached https://files.pythonhosted.org/packages/b1/1d/2476110614367adfb079a9bc718621f9fc8351e9214e1750cae1832d4090/Django-2.2.1-py3-none-any.whl
Collecting pytz (from django)
  Using cached https://files.pythonhosted.org/packages/3d/73/fe30c2daaaa0713420d0382b16fbb761409f532c56bdcc514bf7b6262bb6/pytz-2019.1-py2.py3-none-any.whl
Collecting sqlparse (from django)
  Using cached https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl
Installing collected packages: pytz, sqlparse, django
Successfully installed django-2.2.1 pytz-2019.1 sqlparse-0.3.0
(venv) [root@server01 myproject]# 

安装之后,django库则会保存在venvbin目录下,如下:

此时,在用原生的python3导入django库,看看会不会报错。

(venv) [root@server01 myproject]# ls venv/bin/
activate       activate_this.py  easy_install      pip3.7       python3.7
activate.csh   activate.xsh      easy_install-3.7  __pycache__  python-config
activate.fish  django-admin      pip               python       sqlformat
activate.ps1   django-admin.py   pip3              python3      wheel
(venv) [root@server01 myproject]# python3
Python 3.7.1 (default, May  2 2019, 14:58:59) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> 
>>> django.get_version()
'2.2.1'
>>> 

可以看到已经可以使用了django库了。

那么如何退出这个venv的环境呢?

使用deactivate命令,退出venv的环境

(venv) [root@server01 myproject]# deactivate
[root@server01 myproject]# 
[root@server01 myproject]# 

可以看到左边已经没有显示(venv)的环境了。说明已经退出了独立运行的虚拟环境,回到了系统环境。

其他更多用法

[root@server01 ~]# mkdir project_python2
[root@server01 ~]# cd project_python2/
[root@server01 project_python2]# ls -ll /usr/bin/python
lrwxrwxrwx. 1 root root 7 Mar 31 11:53 /usr/bin/python -> python2
[root@server01 project_python2]# 
[root@server01 project_python2]# virtualenv -p /usr/bin/python py2venv
Running virtualenv with interpreter /usr/bin/python
  No LICENSE.txt / LICENSE found in source
New python executable in /root/project_python2/py2venv/bin/python
Installing setuptools, pip, wheel...
done.
[root@server01 project_python2]# 

[root@server01 ~]# mkdir project_python3
[root@server01 ~]# cd project_python3/
[root@server01 project_python3]# ls
[root@server01 project_python3]# virtualenv --system-site-packages py3venv
Using base prefix '/usr/local/python3'
New python executable in /root/project_python3/py3venv/bin/python3.7
Also creating executable in /root/project_python3/py3venv/bin/python
Installing setuptools, pip, wheel...
done.
[root@server01 project_python3]# 
[root@server01 project_python3]# source py3venv/bin/activate
(py3venv) [root@server01 project_python3]# python3
Python 3.7.1 (default, May  2 2019, 14:58:59) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django    # 直接继承了系统的python第三方库
>>> django.get_version()
'2.2.1'
>>> exit()
(py3venv) [root@server01 project_python3]# 
# 在虚拟环境下,安装redis库
(py3venv) [root@server01 project_python3]# pip3 install redis
Collecting redis
  Downloading https://files.pythonhosted.org/packages/ac/a7/cff10cc5f1180834a3ed564d148fb4329c989cbb1f2e196fc9a10fa07072/redis-3.2.1-py2.py3-none-any.whl (65kB)
     |████████████████████████████████| 71kB 32kB/s 
Installing collected packages: redis
Successfully installed redis-3.2.1
(py3venv) [root@server01 project_python3]# 
# 在虚拟环境下,导入redis库
(py3venv) [root@server01 project_python3]# python3
Python 3.7.1 (default, May  2 2019, 14:58:59) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import redis
>>> 
(py3venv) [root@server01 project_python3]# deactivate 
[root@server01 project_python3]# 
# 退出虚拟环境之后,导入redis失败,说明虚拟环境安装的redis库,是不会安装到系统环境的。
[root@server01 project_python3]# python3
Python 3.7.1 (default, May  2 2019, 14:58:59) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import redis
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'redis'
>>> 

场景:确保共享的项目能够在其他电脑上正常运行
解决:

方案一:
连同虚拟环境和项目一起拷贝给他人

方案二:
在虚拟环境中,冻结依赖需求文本
把项目和依赖需求文本给他人
他人在本地创建一个新的虚拟环境,并根据依赖需求文本安装相关库

技能点:
冻结项目需求文本 pip3 freeze > requirements.txt
根据需求文本,安装项目依赖库 pip3 install -r requirements.txt (在激活的虚拟环境中)

示例操作如下:

[root@server01 project_python3]# pip3 freeze > requirements.txt
[root@server01 project_python3]# ls
py3venv  requirements.txt
[root@server01 project_python3]# cat requirements.txt 
backcall==0.1.0
decorator==4.4.0
Django==2.2.1
ipython==7.5.0
ipython-genutils==0.2.0
jedi==0.13.3
parso==0.4.0
pexpect==4.7.0
pickleshare==0.7.5
prompt-toolkit==2.0.9
ptyprocess==0.6.0
Pygments==2.3.1
pytz==2019.1
six==1.12.0
sqlparse==0.3.0
traitlets==4.3.2
virtualenv==16.6.0
wcwidth==0.1.7
[root@server01 project_python3]# pip3 install -r requirements.txt

生成的步骤,就要用cmd来执行了。

virtualenv的官方文档

更加详细的内容可以访问官方文档

在pycharm使用

上一篇下一篇

猜你喜欢

热点阅读