如何在python shell中激活虚拟环境

时间:2019-02-11 14:14:02

标签: python shell virtualenv

我已经创建了一个虚拟环境(目录为 env )并安装了一些第三方软件包。我使用Mac OSX。如何在 python交互式shell 激活我的venv ?我尝试过

source env/bin/activate

并收到错误消息:SyntaxError: invalid syntax

我已经看到有人在8年前发布了这个问题,但是我没有找到我想要的...我也检查了python文档,但不清楚如何激活它

https://docs.python.org/3/tutorial/venv.html?highlight=virtual

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

在您的shell中,通常python会将您指向python的默认实例:

python

Python 2.7.14 (default, Sep 25 2017, 09:53:22)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

这是因为python位于/usr/local/bin中,这是默认PATH的一部分。现在,当您source activate <some_env>时,您正在修改 PATH,您实际上可以在/path/to/venv/some_env/bin/activate文件中看到:

#!/bin/bash

...

    if [[ $PATH == *"CONDA_PATH_PLACEHOLDER"* ]]; then
        # If it did, replace it with our _NEW_PART
        export PATH="$($_CONDA_PYTHON -c "import re; print(re.sub(r'CONDA_PATH_PLACEHOLDER', r'$_NEW_PART', '$PATH', 1))")"
    else

        #### HERE IS WHERE THAT PATH IS OVERWRITTEN

        export PATH="$_NEW_PART:$PATH"
    fi

    # CONDA_DEFAULT_ENV is the shortest representation of how conda recognizes your env.
    #    It can be an env name, or a full path.
    #    Last date of change: 2016-06-21
    # If the string contains / it's a path
    if [[ "$@" == */* ]]; then
        export CONDA_DEFAULT_ENV=$(get_abs_filename "$args")
    else
        export CONDA_DEFAULT_ENV="$args"
    fi
...
esac

我使用的是anaconda,但是概念是相同的,...表示我在其中摘录了部分脚本。它正在有效地将venv python可执行路径导出到PATH中。因此,除非出现以下两种情况之一,否则您将不会指向venv python:a)您显式调用该python可执行文件,或b)source activate myenv然后 then 调用{ {1}}。

因此正确的工作流程是:

python

然后打电话 source /path/to/myenv/bin/activate myenv

例如,在激活我的conda env之前,第一次调用python ,之后是第二次:

$PATH

请注意➜ ~ echo $PATH /Users/mm92400/bin:/usr/local/bin:/Users/mm92400/anaconda3/bin:/Users/mm92400/.cargo/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/usr/local/share/dotnet:~/.dotnet/tools:/Library/Frameworks/Mono.framework/Versions/Current/Commands ➜ ~ source activate py36 (py36) ➜ ~ echo $PATH /Users/mm92400/anaconda3/envs/py36/bin:/Users/mm92400/bin:/usr/local/bin:/Users/mm92400/anaconda3/bin:/Users/mm92400/.cargo/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/usr/local/share/dotnet:~/.dotnet/tools:/Library/Frameworks/Mono.framework/Versions/Current/Commands 与众不同