Python虚拟环境无法从bash脚本激活

时间:2018-06-18 15:57:16

标签: python-3.x bash virtualenv

现在,在您将此标记为重复之前,我已尝试过解决方案posted here,但他们并不适合我。我尝试制作别名,我尝试创建一个函数:

activate () {
    echo Activating Virtual Environment...
    source alexa/bin/activate
}
activate

但是我的脚本只是在没有激活虚拟环境的情况下运行。该脚本从与我的虚拟环境目录alexa相同的目录运行。

为清楚起见,我尝试的另一个解决方案是创建一个别名:

alias activate="source alexa/bin/activate"
activate

那不起作用并给我一个错误./alexaEnvSetup.sh: line 43: activate: command not found

有什么想法或想法吗?

编辑:我认为值得一提的是,当我这样做时,echo命令会打印出来。所以功能正在进入。虚拟环境没有被激活。

编辑:添加完整代码:

#!/bin/bash

if [[ "$OSTYPE" == "linux-gnu" ]]; then
    echo Operating system: Linux
elif [[ "$OSTYPE" == "darwin"* ]]; then
    echo Operating system: Mac OSX
    echo

    # Install Python 3.6.5 using `curl`
    curl -O https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tgz
    tar xf Python-3.6.5.tgz
    cd Python-3.6.5
    ./configure
    make
    make install

    echo
    echo Python Version 3.6.5 Installed
    echo

    # Install Pip
    curl -O http://bootstrap.pypa.io/get-pip.py
    /usr/local/bin/python3.6 get-pip.py

    echo
    echo Pip Installed
    echo

    # Install virtualenv
    pip install virtualenv

    echo
    echo Virtual Environment Installed

    virtualenv -p python3 alexa
    echo Created Virtual Environment, \"alexa\"

    activate () {
        echo Activating Virtual Environment...
        source /Users/XXXX/Auto-Lab/Commerce/alexa/bin/activate
    }
    export -f activate
    activate

    echo Virtual Environment, \"alexa\", Created and Activated
    echo

    # All packages (time, urllib, and json) should come default with Python3

elif [[ "$OSTYPE" == "cygwin" ]]; then
    # POSIX compatibility layer and Linux environment emulation for Windows
    echo Operating system: Cygwin
elif [[ "$OSTYPE" == "msys" ]]; then
    # Lightweight shell and GNU utilities compiled for Windows (part of MinGW)
    echo Operating system: Msys
elif [[ "$OSTYPE" == "win32" ]]; then
    echo Operating system: Windows32
elif [[ "$OSTYPE" == "freebsd"* ]]; then
    echo Operating system: FreeBSD
else
    echo Operating system unknown.
fi

2 个答案:

答案 0 :(得分:0)

  1. 使用完整路径到函数中的激活脚本:source /path/to/activate
  2. 导出功能:export -f activate
  3. 确保脚本是bash脚本:#!/bin/bash

答案 1 :(得分:0)

以下适用于我使用Anaconda虚拟环境,也许它也适用于你的?

#!/usr/bin/env bash

# do bash stuff

# Python env
PATH=/home/username/path/to/activate/bin
python -u /script/to/run