• 搭建Python虚拟环境


    虚拟环境

    概述

    为什么需要搭建Python的虚拟环境?

    正常情况下,在一台电脑上, 想开发多个不同的项目, 需要用到同一个包的不同版本, 如果使用pip install 包名称pip install 包名称==版本号命令, 在同一个目录下安装或者更新, 新版本会覆盖以前的版本, 就会导致其它的项目就无法运行

    虚拟环境的优点:

    1. 虚拟环境可以搭建独立的python运行环境, 使单个项目的运行环境与其它项目互不影响。

    2. 虚拟环境中的安装的第三方依赖包和全局环境中的包相互独立。

    3. 虚拟环境能防止出现包管理混乱和版本冲突。

    4. 虚拟环境不会影响全局的python环境

    virtualenv

    virtualenv是一个 Python 应用程序,它可以创建独立的Python环境,每个环境有自己的Python解释器和Python包。

    使用virtualenv可以避免在同一系统上的多个应用程序之间发生冲突,并使开发人员能够更轻松地管理他们的应用程序所依赖的Python包。

    virtualenv常用命令说明

    创建虚拟环境:

    # 在当前目录下创建一个名为 myenv 的虚拟环境
    
    virtualenv myenv
    
    • 1
    • 2
    • 3

    激活虚拟环境 (Windows):

    # 激活后,终端前会显示 (myenv) 字样,说明已处于虚拟环境中
    
    myenv\Scripts\activate.bat
    
    • 1
    • 2
    • 3

    激活虚拟环境 (Linux/MacOS):

    source myenv/bin/activate
    
    • 1

    退出虚拟环境:

    deactivate
    
    • 1

    virtualenvwrappervirtualenv的扩展,它是一组Shell脚本,提供了更便捷的方式来创建、删除、复制和切换Virtualenvs。

    它的目标是让用户能够更快地使用virtualenv,同时还提供了其他有用的功能,如在终端中列出所有的虚拟Python环境、自动切换到虚拟环境等。

    安装虚拟环境

    Windows环境下

    执行如下命令安装虚拟环境

    pip install virtualenv
    
    pip install virtualenvwrapper-win
    
    • 1
    • 2
    • 3

    配置虚拟环境目录

    如在D:\Development\Python\目录下创建env目录用于存放虚拟环境,然后在配置环境变量

    WORKON_HOME
    
    D:\Development\Python\env
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    Linux环境下

    执行如下命令安装虚拟环境

    pip install virtualenv
    
    pip install virtualenvwrapper
    
    • 1
    • 2
    • 3

    注意:

    在执行pip3 install virtualenvwrapper命令安装virtualenvwrapper时可能失败,具体异常如下:

    [root@administrator ~]# pip3 install virtualenvwrapper
    Looking in indexes: https://pypi.douban.com/simple/
    Collecting virtualenvwrapper
      Using cached https://pypi.doubanio.com/packages/c1/6b/2f05d73b2d2f2410b48b90d3783a0034c26afa534a4a95ad5f1178d61191/virtualenvwrapper-4.8.4.tar.gz (334 kB)
      Preparing metadata (setup.py) ... error
      error: subprocess-exited-with-error
      
      × python setup.py egg_info did not run successfully.
      │ exit code: 1
      ╰─> [43 lines of output]
          /usr/local/python3/lib/python3.9/site-packages/setuptools/dist.py:717: UserWarning: Usage of dash-separated 'index-url' will not be supported in future versions. Please use the underscore name 'index_url' instead
            warnings.warn(
          /usr/local/python3/lib/python3.9/site-packages/setuptools/dist.py:717: UserWarning: Usage of dash-separated 'author-email' will not be supported in future versions. Please use the underscore name 'author_email' instead
            warnings.warn(
          /usr/local/python3/lib/python3.9/site-packages/setuptools/dist.py:717: UserWarning: Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead
            warnings.warn(
          /usr/local/python3/lib/python3.9/site-packages/setuptools/dist.py:717: UserWarning: Usage of dash-separated 'home-page' will not be supported in future versions. Please use the underscore name 'home_page' instead
            warnings.warn(
          WARNING: The wheel package is not available.
          WARNING: The repository located at mirrors.cloud.aliyuncs.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.cloud.aliyuncs.com'.
          ERROR: Could not find a version that satisfies the requirement pbr (from versions: none)
          ERROR: No matching distribution found for pbr
          Traceback (most recent call last):
            File "/usr/local/python3/lib/python3.9/site-packages/setuptools/installer.py", line 75, in fetch_build_egg
              subprocess.check_call(cmd)
            File "/usr/local/python3/lib/python3.9/subprocess.py", line 373, in check_call
              raise CalledProcessError(retcode, cmd)
          subprocess.CalledProcessError: Command '['/usr/bin/python3', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', '/tmp/tmp4jxzlf_y', '--quiet', '--index-url', 'http://mirrors.cloud.aliyuncs.com/pypi/simple/', 'pbr']' returned non-zero exit status 1.
          
          The above exception was the direct cause of the following exception:
          
          Traceback (most recent call last):
            File "", line 2, in <module>
            File "", line 34, in <module>
            File "/tmp/pip-install-hjtmzrft/virtualenvwrapper_836b613d97fe4215bcf97055355c9885/setup.py", line 5, in <module>
              setup(
            File "/usr/local/python3/lib/python3.9/site-packages/setuptools/__init__.py", line 152, in setup
              _install_setup_requires(attrs)
            File "/usr/local/python3/lib/python3.9/site-packages/setuptools/__init__.py", line 147, in _install_setup_requires
              dist.fetch_build_eggs(dist.setup_requires)
            File "/usr/local/python3/lib/python3.9/site-packages/setuptools/dist.py", line 806, in fetch_build_eggs
              resolved_dists = pkg_resources.working_set.resolve(
            File "/usr/local/python3/lib/python3.9/site-packages/pkg_resources/__init__.py", line 766, in resolve
              dist = best[req.key] = env.best_match(
            File "/usr/local/python3/lib/python3.9/site-packages/pkg_resources/__init__.py", line 1051, in best_match
              return self.obtain(req, installer)
            File "/usr/local/python3/lib/python3.9/site-packages/pkg_resources/__init__.py", line 1063, in obtain
              return installer(requirement)
            File "/usr/local/python3/lib/python3.9/site-packages/setuptools/dist.py", line 877, in fetch_build_egg
              return fetch_build_egg(self, req)
            File "/usr/local/python3/lib/python3.9/site-packages/setuptools/installer.py", line 77, in fetch_build_egg
              raise DistutilsError(str(e)) from e
          distutils.errors.DistutilsError: Command '['/usr/bin/python3', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', '/tmp/tmp4jxzlf_y', '--quiet', '--index-url', 'http://mirrors.cloud.aliyuncs.com/pypi/simple/', 'pbr']' returned non-zero exit status 1.
          [end of output]
      
      note: This error originates from a subprocess, and is likely not a problem with pip.
    error: metadata-generation-failed
    
    × Encountered error while generating package metadata.
    ╰─> See above for output.
    
    note: This is an issue with the package mentioned above, not pip.
    hint: See above for details.
    
    [notice] A new release of pip is available: 23.0.1 -> 23.1.2
    [notice] To update, run: python3 -m pip install --upgrade pip
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    原因:

    缺少相关的依赖:virtualenvwrapper需要一些系统库来正常工作,例如python-devel、gcc等。

    使用以下命令安装所有必需的系统库:

    sudo yum install python3-devel gcc
    
    • 1

    在安装依赖库后,执行pip3可能如下如下异常:

    [root@administrator ~]# pip3 -V
    Traceback (most recent call last):
      File "/usr/local/bin/pip3", line 5, in <module>
        from pip._internal.cli.main import main
    ModuleNotFoundError: No module named 'pip._internal'
    
    • 1
    • 2
    • 3
    • 4
    • 5

    根据提示,修改/usr/local/bin/pip3文件

    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    import re
    import sys
    from pip import main # 修改这行,原来:from pip._internal import main
    if __name__ == '__main__':
        sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
        sys.exit(main())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    接着执行pip3 -V验证哈,没问题继续安装,看到出现如下进度条,就没问题了

    [root@administrator ~]# pip3 install virtualenvwrapper
    WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
    Collecting virtualenvwrapper
      Cache entry deserialization failed, entry ignored
      Cache entry deserialization failed, entry ignored
      Downloading https://pypi.doubanio.com/packages/c1/6b/2f05d73b2d2f2410b48b90d3783a0034c26afa534a4a95ad5f1178d61191/virtualenvwrapper-4.8.4.tar.gz (334kB)
        100% |████████████████████████████████| 337kB 2.0MB/s 
    Collecting virtualenv (from virtualenvwrapper)
      Cache entry deserialization failed, entry ignored
      Downloading https://pypi.doubanio.com/packages/18/a2/7931d40ecb02b5236a34ac53770f2f6931e3082b7a7dafe915d892d749d6/virtualenv-20.17.1-py3-none-any.whl (8.8MB)
        100% |████████████████████████████████| 8.9MB 150kB/s 
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    注意:

    若安装完虚拟环境后,提示找不到mkvirtualenv命令,就必须配置环境变量

    创建目录用来存放虚拟环境

    mkdir 
    
    $HOME/.virtualenvs
    
    • 1
    • 2
    • 3

    打开~/.bashrc文件,添加环境变量信息

    export WORKON_HOME=$HOME/.virtualenvs
    
    source /usr/local/bin/virtualenvwrapper.sh
    
    • 1
    • 2
    • 3

    使配置生效

    source ~/.bashrc
    
    • 1

    执行source ~/.bashrc命令时,可能出现如下异常:

    [root@administrator ~]# source ~/.bashrc
    /usr/bin/python: No module named virtualenvwrapper
    virtualenvwrapper.sh: There was a problem running the initialization hooks.
    
    If Python could not import the module virtualenvwrapper.hook_loader,
    check that virtualenvwrapper has been installed for
    VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is
    set properly.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    打开~/.bashrc文件,添加环境变量,指定virtualenvwrapper使用python3

    export WORKON_HOME=$HOME/.virtualenvs
    
    export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
    
    source /usr/local/bin/virtualenvwrapper.sh
    
    • 1
    • 2
    • 3
    • 4
    • 5

    创建虚拟环境

    如果不指定python版本,默认安装的是python2的虚拟环境

    python2中创建虚拟环境

    mkvirtualenv 虚拟环境名称
    
    • 1

    在python3中创建虚拟环境

    mkvirtualenv -p python3 虚拟环境名称
    
    • 1

    创建成功之后,默认会自动进入到虚拟环境

    C:\Users\JackChen>mkvirtualenv -p python3 py3
    created virtual environment CPython3.9.5.final.0-64 in 3711ms
      creator CPython3Windows(dest=D:\Development\Python\env\py3, clear=False, no_vcs_ignore=False, global=False)
      seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\JackChen\AppData\Local\pypa\virtualenv)
        added seed packages: pip==22.3.1, setuptools==65.6.3, wheel==0.38.4
      activators BashActivator,BatchActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
    
    (py3) C:\Users\JackChen>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    使用虚拟环境

    查看虚拟环境

    (py3) C:\Users\JackChen>workon
    
    Pass a name to activate one of the following virtualenvs:
    ==============================================================================
    demo
    py3
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    使用虚拟环境

    workon  虚拟环境名称
    
    • 1
    (py3) C:\Users\JackChen>workon demo
    (demo) C:\Users\JackChen>
    
    • 1
    • 2

    退出虚拟环境

    deactivate
    
    • 1

    删除虚拟环境

    注意:不能删除正在使用的虚拟环境,需要退出/切换其他虚拟环境后才可以删除

    rmvirtualenv 虚拟环境名称
    
    • 1

    虚拟机环境下安装包

    在虚拟环境中安装包

    pip install 包名称
    
    • 1

    查看虚拟环境中安装的包

    pip list
    
    • 1

    在虚拟环境中卸载包

    pip uninstall 包名称
    
    • 1

    PyCharm中使用虚拟环境

    在PyCharm中如何使用创建的虚拟环境呢?

    首先找到pycharm的设置选项,选择虚拟环境

    在这里插入图片描述
    若没有响应虚拟环境,则需要添加虚拟环境
    在这里插入图片描述

  • 相关阅读:
    SQL数据库添加新账号,只操作指定数据库
    python项目源码基于django的宿舍管理系统dormitory+mysql数据库文件
    Java基础篇--XML简介
    高速串行信号串接电容放在发送端还是接收端
    15、青年歌手大赛_评委打分
    使用Spark SQL读取阿里云OSS的数据
    万应低代码CTO胡艳平:赛道的喧嚣,带来的几个概念混淆
    湖南工商大学------函数及其应用
    JVM:字节码文件,类的生命周期,类加载器
    Java编程实战9:统计只差一个字符的子串数目
  • 原文地址:https://blog.csdn.net/qq_38628046/article/details/128155738