what shebang to use for python scripts run under a pyenv virtualenv

前端 未结 5 1758
攒了一身酷
攒了一身酷 2020-12-08 18:34

When a python script is supposed to be run from a pyenv virtualenv what is the correct shebang for the file?

As an example test case, the d

5条回答
  •  我在风中等你
    2020-12-08 19:02

    As you expected, you should be able to use the full path to the virtual environment's python in the shebang to choose/control the environment the script runs in regardless of the environment of the controlling script.

    In the comments on your question, VPfB & you find that the /Users/username/.pyenv/shims/python is a shell script that does an exec $pyenv_python. You should be able to echo $pyenv_python to determine the real python and use that as your shebang.

    See also: https://unix.stackexchange.com/questions/209646/how-to-activate-virtualenv-when-a-python-script-starts

    Try pyenv virtualenvs to find a list of virtual environment directories.

    And then you might find a using shebang something like this:

    #!/Users/username/.pyenv/python/versions/venv_name/bin/python
    import pandas as pd
    print 'success'
    

    ... will enable the script to work using the chosen virtual environment in other (virtual or not) environments:

    (venv_name) $ ./script.py 
    success
    (venv_name) $ pyenv activate non_pandas_venv 
    (non_pandas_venv) $ ./script.py
    success
    (non_pandas_venv) $ . deactivate
    $ ./script.py
    success
    $
    

    The trick is that if you call out the virtual environment's python binary specifically, python looks around that binary's path location for the supporting files and ends up using the surrounding virtual environment. (See per How does virtualenv work? )

提交回复
热议问题