Search code examples
pythonupgradevirtualenvwrapper

What is the best way to upgrade python in a virtual environment using virtualenvwrapper?


I created an environment using virtualenvwrapper while my machine was running Python 3.8.3. Naturally, this made the environment with Python 3.8.3 as well.

Later, I updated Python on my main machine using home brew to 3.10.

Now I have 3.10-specific code in the virtual env project, running 3.8.3.

The first entry in that project's $PATH is set to the virtual env itself, which uses the old Python. The 2nd entry is Python 3.10. I believe this is standard. The virtual env itself is added to the front of $PATH by virtualenverapper upon activation.

Short of manually manipulating the .zprofile or a virtalenvwrapper's postactivate script, I am wondering if there is a more sweeping and automatic way of updating a virtual environment using virtualenvwarpper?

I am no expert on this stuff, so my concern is that manually manipulating files, or applying one-time fixes will just be asking for trouble down the line.

Thanks for your help.

EDIT: I wanted to add that I am also learning git and have a repo set up in this project. I would like to ideally preserve that information through the "upgrade," which it sounds like involves creating a new env. The virtualenvs are stored on the ~user directory in .virtualenvs. The git repo is in the project directory.


Solution

  • You don't want to do this. As you said, even if you pulled it off you're sure to have hidden issues that'll be a major headache down the line. Fortunately, it's very easy to recreate the virtual env with exactly the same installed packages you had before but with a new Python version.

    What you want is to compile a list of installed packages in your old virtualenv, make your new venv with the desired Python version, then reinstall all the packages. We can do this simply like this :

    workon oldenv
    pip freeze > env_requirements.txt
    deactivate
    mkvirtualenv newenv -p `which python3.10`
    pip install -r env_requirements.txt
    

    If you're happy with the result, you can then delete the old venv :

    rmvirtualenv oldenv
    

    As to your concern with git, this should have absolutely no impact whatsoever on your git repo.