2
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

Organization

Python の venv を自動で有効(無効)化させたい

どうやって自動化するのが一般的なんだろうか?

仮想環境の名前は常に .venv であるという仮定。

$ python3.6 -m venv .venv

例えば cd にフックして自動化するとして、zsh のフックを使う場合は以下の様な感じで良いのだろうか?

function chpwd_pyvenv() {
    cwd=$(pwd)

    while :
    do
        if [ -d "${cwd}/.venv" ]; then
            echo "Python venv found: ${cwd}/.venv"
            if [ "${VIRTUAL_ENV}" != "${cwd}/.venv" ]; then
                echo "Python venv activated: ${cwd}/.venv"
                source ${cwd}/.venv/bin/activate
            else
                echo "Python venv already activated: ${cwd}/.venv"
            fi
            break
        fi

        if [ "${cwd}" = "/" ]; then
            echo "Python venv not found: ${cwd}.venv"
            if [ -n "${VIRTUAL_ENV}" ]; then
                echo "Python activated venv deactivate: ${VIRTUAL_ENV}"
                deactivate
            fi
            break
        fi

        cwd=$(dirname $cwd)
    done
}

add-zsh-hook chpwd chpwd_pyvenv

direnvzsh-autoenv などのツールを使う方が賢いだろうか?もしくは pyenvpyenv-virtualenv の様なツールを使うのだろうか?

Python 界のデファクトでスマートな解決策が知りたい。

2017/08/19 追記

fish shell の場合はイベントハンドラでやるのかな?

~/.config/fish/functions/auto_virtualenv.fish
function auto_virtualenv --on-variable PWD
    set cwd $PWD

    while true
        if [ -d "$cwd/.venv" ]
            echo "Python venv found: $cwd/.venv"
            if [ "$VIRTUAL_ENV" != "$cwd/.venv" ]
                echo "Python venv activated: $cwd/.venv"
                source $cwd/.venv/bin/activate.fish
            else
                echo "Python venv already activated: $cwd/.venv"
            end
            break
        end

        if [ "$cwd" = "/" ]
            echo "Python venv not found."
            if [ -n "$VIRTUAL_ENV" ]
                echo "Python activated venv deactivate: $VIRTUAL_ENV"
                deactivate
            end
            break
        end

        set cwd (dirname $cwd)
    end

end

参考

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
2
Help us understand the problem. What are the problem?