Python venv或virtualenv模块-创建、激活、退出虚拟环境

1、venv介绍

virtualenv用于创建独立的Python环境,多个Python相互独立,互不影响。

2、虚拟环境管理【内置模块】

2.1、创建虚拟环境

# 创建venv虚拟环境
[root@ansible-control ~]# cd /usr/local/Python-3.10.10/ && python3 -m venv 'tornado-env'

# 检查是否存在
[root@ansible-control Python-3.10.10]# ll
drwxr-xr-x 2 root root 238 Feb 19 21:24 bin
drwxr-xr-x 3 root root  24 Feb 19 21:11 include
drwxr-xr-x 4 root root  64 Feb 19 21:11 lib
drwxr-xr-x 3 root root  17 Feb 19 21:11 share
drwxr-xr-x 5 root root  74 Feb 22 20:19 tornado-env

2.2、激活虚拟环境

[root@ansible-control ~]# source /usr/local/Python-3.10.10/tornado-env/bin/activate
(tornado-env) [root@ansible-control ~]# 

2.3、关闭虚拟环境

(tornado-env) [root@ansible-control ~]# deactivate 
[root@ansible-control ~]# 

3、虚拟环境管理【virtualenv模块】

3.1、创建虚拟环境

3.1.1、创建默认模块venv

# 创建虚拟环境
[root@ansible-control ~]# pip3 install virtualenv

# 查看创建的目录
[root@ansible-control ~]# cd /usr/local/Python-3.10.10/ && /usr/local/Python-3.10.10/bin/virtualenv flask-env
[root@ansible-control Python-3.10.10]# ll
drwxr-xr-x 2 root root 256 Feb 22 20:24 bin
drwxr-xr-x 4 root root  64 Feb 22 20:31 flask-env
drwxr-xr-x 3 root root  24 Feb 19 21:11 include
drwxr-xr-x 4 root root  64 Feb 19 21:11 lib
drwxr-xr-x 3 root root  17 Feb 19 21:11 share

3.1.2、将所有安装模块都打包到新的venv

[root@ansible-control Python-3.10.10]# cd /usr/local/Python-3.10.10/ && /usr/local/Python-3.10.10/bin/virtualenv --system-site-packages flask-env

3.2、激活虚拟环境

[root@ansible-control ~]# source /usr/local/Python-3.10.10/flask-env/bin/activate
(flask-env) [root@ansible-control ~]# 

3.3、关闭虚拟环境

(flask-env) [root@ansible-control ~]# deactivate 
[root@ansible-control ~]# 

 

posted @ 2023-02-22 20:46  小粉优化大师  阅读(634)  评论(0编辑  收藏  举报