Calling IPython from a virtualenv

前端 未结 8 2001
既然无缘
既然无缘 2020-12-12 13:34

I understand that IPython is not virtualenv-aware and that the most logical solution to this is to install ipython in each virtualenv seperately using

pip i         


        
8条回答
  •  悲哀的现实
    2020-12-12 14:05

    I'll chime in years later in hopes someone finds this useful.

    This solution solves a few problems:

    • You don't need iPython installed in the current virtualenv, only for the global Python that matches your virtualenv's Python version (3.6 != 3.7).
    • Works for users of pyenv where your global Python version might be 3.7 and your local virtualenv Python is 3.6 therefore using the global ipython will fail.
    • Works outside of virtual environments (though not particularly useful as it always targets python).

    Throw this in your ~/.bashrc or ~/.zshrc or what have you:

    # This is a roundabout way to start ipython from inside a virtualenv without it being installed
    # in that virtualenv. The only caveot is that the "global" python must have ipython installed.
    # What this function does that's different than simply calling the global ipython is it ensures to
    # call the ipython that is installed for the same major.minor python version as in the virtualenv.
    # This is most useful if you use pyenv for example as global python3 could be 3.7 and local
    # virtualenv python3 is 3.6.
    function ipy {
      local PY_BIN
      local IPYTHON
      local PYV
      # This quick way will work if ipython is in the virtualenv
      PY_BIN="$(python -c 'import sys; print(sys.executable)')"
      IPYTHON="$(dirname "$PY_BIN")/ipython"
      if [[ -x "$IPYTHON" ]]; then
        "$IPYTHON"
      else
        # Ask the current python what version it is
        PYV="$(python -c 'import sys; print(".".join(str(i) for i in sys.version_info[:2]))')"
        echo "Looking for iPython for Python $PYV"
        # In a new shell (where pyenv should load if equipped) try to find that version
        PY_BIN="$($SHELL -i -c "python$PYV -c 'import sys; print(sys.executable)'")"
        "$(dirname "$PY_BIN")/ipython"
      fi
    }
    

    Then source or open a new terminal and run ipy.

提交回复
热议问题