How do I use different Python version in venv from standard library? (Not virtualenv!)

后端 未结 3 1580
耶瑟儿~
耶瑟儿~ 2020-12-14 02:06

I have installed Python 3.4.0 and created virtual environment with python -m venv myenv. How can I change Python version in my virtual environment? Documentati

3条回答
  •  死守一世寂寞
    2020-12-14 02:22

    On Linux/Mac you can easily install multiple versions of Python next to the main one and you can use the venv package from the standard library to create virtual environments from each version >= 3.3.

    Create venv

    $ python3.3 -m venv myvenv_foo  # Create a python3.4 venv named 'myvenv_foo'
    $ python3.4 -m venv myvenv_bar  # Create a python3.4 venv named 'myvenv_bar'
    $ python3.5 -m venv myvenv_baz  # Create a python3.5 venv named 'myvenv_baz'
    # etc...
    

    Activate venv

    source myvenv_foo/bin/activate  # Activates venv 'myvenv_foo'
    

    Deactivate venv

    deactivate
    

    Notice: python vs pythonX.X

    If you have multiple Python versions installed, you can access each one by adding the version num to the command e.g. python3.5, python3.6, etc. But keep in mind that when you activate a venv, you bind it to the clean/versionless python command, for as long as it's activated. E.g:

    $ python -V # Use the *clean* 'python' command to show the main version of the OS.
    Python 2.7.6 
    $ python3.5 -m venv myvenv_foo # Create a new venv from 'python3.5'.
    $ source myvenv_foo/bin/activate # Activate venv.
    $ python -V # The *clean* 'python' command is now bound to your activated venv.
    Python 3.5.2 
    $ deactivate  # Deactivate venv.
    $ python -V  # Now the *clean* command is bound back to the main version.
    Python 2.7.6 
    

    Note

    I suggest using Pipenv to create/handle virutal environments over the venv package.

    From the offical docs:

    Managing multiple virtual environments directly can become tedious, so the dependency management tutorial introduces a higher level tool, Pipenv, that automatically manages a separate virtual environment for each project and application that you work on.

提交回复
热议问题