目录

1.背景

2.创建虚拟环境

3.目录结构

4.pip安装

5.环境使用


1.背景

很多应用、开源软件都是python写的,各自有各自的软件包和版本依赖,有事可能会有所冲突,为了避免这个冲突,建议采用venv虚拟环境。

本文讲解venv虚拟环境如何搭建、如何进行依赖包安装及如何使用。

测试环境:centos7

2.创建虚拟环境

创建虚拟环境命令格式

python -m venv 虚拟环境名

创建虚拟环境到venvtest目录

python -m venv venvtest

 

3.目录结构

进入目录看一下

[root@localhost ~]# cd venvtest/

[root@localhost venvtest]# ls

bin include lib lib64 pyvenv.cfg

[root@localhost venvtest]# ls bin/

activate activate.csh activate.fish easy_install easy_install-3.6 pip pip3 pip3.6 python python3

[root@localhost venvtest]# ls lib

python3.6

[root@localhost venvtest]# ls lib/python3.6/site-packages/

easy_install.py pip-9.0.3.dist-info __pycache__ setuptools-39.2.0.dist-info

pip pkg_resources setuptools

可以看到,就是一个干净的环境

4.pip安装

使用pip安装包

先看下pip位置和版本

[root@localhost venvtest]# bin/pip3 -V

pip 9.0.3 from /root/venvtest/lib64/python3.6/site-packages (python 3.6)

[root@localhost venvtest]# bin/pip3 install requests

……

安装好后

[root@localhost venvtest]# ls lib/python3.6/site-packages/

certifi idna __pycache__ urllib3

certifi-2019.11.28.dist-info idna-2.9.dist-info requests urllib3-1.25.8.dist-info

chardet pip requests-2.23.0.dist-info

chardet-3.0.4.dist-info pip-9.0.3.dist-info setuptools

easy_install.py pkg_resources setuptools-39.2.0.dist-info

发现包已经安装到虚拟环境中了

5.环境使用

[root@localhost venvtest]# vi test.py

不多,就放如下两行代码,用于验证requests包是否存在(真实环境中没有安装这个包)

import requests

print("hello")

运行验证下

[root@localhost venvtest]# bin/python test.py

hello

[root@localhost venvtest]# python3 test.py

Traceback (most recent call last):

File "test.py", line 1, in <module>

import requests

ModuleNotFoundError: No module named 'requests'

第一步说明虚拟环境运行成功。

第二步说明真实环境中找不到requests包。