3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-08-15

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

仮想環境の名前は常に .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

参考

3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?