ubantu18.04 安装 virtualenvwrapper

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/weixin_38417098/article/details/86004118

virtualenvwrapper

virtualenvwrapper 是一个基于virtualenv之上的工具,统一管理所有虚拟环境。

环境:ubantu18.04, python3.6,pip3

  1. 安装

    # 安装python3时已经安装 virtualenv 
    sudo pip3 install virtualenvwrapper
    
  2. 启动virtualenvwrapper

    source /usr/local/bin/virtualenvwrapper.sh
    
    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.
    

    报以上的错误原因是:Ubuntu安装了2.7和3.x两个版本的python,在安装时使用的是sudo pip3 install virtualenvwrapper在我运行的时候默认使用的是python2.x,但在python2.x中不存在对应的模块。

    找到virtualenvwrapper.sh文件,打开,找到这段话:

    # Locate the global Python where virtualenvwrapper is installed.
    if [ "$VIRTUALENVWRAPPER_PYTHON" = "" ] then
        VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
    fi
    

    这段话表明当不存在VIRTUALENVWRAPPER_PYTHON环境时,会默认选择使用which python(我这里默认是python2,而ubantu18.04不会默认安装python2)

    更改为:

    if [ "$VIRTUALENVWRAPPER_PYTHON" = "" ] then
        VIRTUALENVWRAPPER_PYTHON="$(command \which python3)"
    fi
    
  3. 配置virtualenvwrapper,可以直接使用

    sudo gedit ~/.bashrc
    

    .bashrc

    ...
    if [ `id -u` != '0' ]; then
    
      export VIRTUALENV_USE_DISTRIBUTE=1        # <-- Always use pip/distribute
      export WORKON_HOME=$HOME/.virtualenvs       # <-- Where all virtualenvs will be stored
      source /usr/local/bin/virtualenvwrapper.sh
      export PIP_VIRTUALENV_BASE=$WORKON_HOME
      export PIP_RESPECT_VIRTUALENV=true
    
    fi
    

    读入配置文件

    source ~/.bashrc
    
    ERROR: virtualenvwrapper could not find virtualenv in your path
    

    出现这种错误,是因为 virtualenv 这个基础依赖包被安装在默认 Python 目录下

    方法1,做一个软连接 ln -s

    #  找到"virtualenv" 位置
    sudo find / -name "virtualenv"
    /home/adamstream/.local/bin/virtualenv
    # 进行软连接
    sudo ln -s /home/adamstream/.local/bin/virtualenv /usr/bin/virtualenv
    
    

    方法2,~/.bashrc中添加一句 :PATH=$PATH: virtualenv所在路径

    PATH=$PATH:~/.local/bin
    

    重新读入配置文件

    source ~/.bashrc
    

创建虚拟环境

mkvirtualenv venv                        # venv为虚拟环境名
mkvirtualenv -p /usr/bin/python3.6 venv  # 指定python版本,venv为虚拟环境名

基本命令:

workon             # 查看当前的虚拟环境目录
workon 虚拟环境名   # 切换到虚拟环境
deactivate         # 退出虚拟环境
rmvirtualenv venv  # 删除虚拟环境venv

猜你喜欢

转载自blog.csdn.net/weixin_38417098/article/details/86004118