如何通过 linux 脚本激活 python env?

How to activate python env via linux script?

系统:


你好,这是我的虚拟环境激活路径,目前正在 运行ning 一个 django 应用程序。

/home/username/.local/env_myapp/bin/activate

if 运行 命令

$ source /home/username/.local/env_myapp/bin/activate

env$ (my_env) 在终端中启动。

我想写一个小脚本来自动启动环境,而不是每次都在控制台中输入整个路径。

所以我查看了 activate 文件...

# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly

好的,所以你在我的脚本中写了这几行。

my_env

 #!/usr/bin/bash
source /home/username/.local/env_myapp/bin/activate
echo "check - activate env"
exit

问题


那么如何通过linux脚本正确激活python环境呢?


亲爱的 Whosebug,这个问题是关于如何通过脚本启动 env,而不是关于 exit - 因为您将其标记为重复。此外,我的问题下的评论解决了任何问题,但我无法“解决”它。所以在下面写了一个答案 - 请参阅“更新”并记入答案。

更新

感谢@Charles Duffy @alaniwi

source /home/username/.local/env_myapp/bin/activate
echo "check - activate env"

现在脚本在终端中启动我的环境。

(知道如何通过问题评论关闭问题。所以我在这里写了@Charles Duffy @alaniwi 的答案)

So how to activate python env via linux script correctly?

阅读Advanced Linux Programming, syscalls(2) and execve(2)(除了/sbin/init之外几乎每个Linux程序都以execve开始)。

所以你可能shebang, so #!/usr/bin/python (and make it executable with chmod(1)启动你的python脚本。

注意你的 $PATH variable (see environ(7) and exec(3))。

你的Unix shell is probably GNU bash (see also getpwent(3) and passwd(5)), so read its documentation (I personally prefer zsh) or at least bash(1)

您可以添加一个 shell 功能,当您 cd 进入目录时自动激活环境。 (这假设你的 pyenv 在 Python 项目目录中,而不是在你的 $HOME/pyenv 之类的目录中。)

# Automatically en/dis-able Python virtual environments:
function cd() {
    builtin cd "$@"
    set_python_env
}

function set_python_env() {
    env=".pyenv"
    if [[ -z "$VIRTUAL_ENV" ]]
    then
        # If env folder is found then activate the virtual env. This only
        # works when cd'ing into the top level Python project directory, not
        # straight into a sub directory. This is probably the common use
        # case as Python depends on the directory hierarchy.
        if [[ -d "$env" ]]
        then
            VIRTUAL_ENV_DISABLE_PROMPT=1
            source "$env/bin/activate"
        fi
    else
        # Check the current folder belong to the current VIRTUAL_ENV. If
        # yes then do nothing, else deactivate, and possibly re-activate if
        # we switched to another venv.
        parentdir="$(dirname "$VIRTUAL_ENV")"
        if [[ "$PWD"/ != "$parentdir"/* ]]
        then
            deactivate
            set_python_env
        fi
    fi
}

# Activate an environment immediately; that way it's activated when you
# open the Terminal and it starts you in the Python project directory.
set_python_env

将以上内容复制到您的 ~/.bashrcsource 中。