5

It would be really convenient to be able to update a virtual environment produced with virtualenv --system-site-packages /path/to/myvirtenv taking into account changes that have been done in the base Python.

For example, if IPython 2.4 has been installed in the virtualenv and IPython 3.0 has later been installed in the base Python, the old IPython should be removed from the virtual environment and replaced by a copy of the newer package.

How can we do this? Is there already a command to do this? If not, would it be possible to implement it in the package virtualenv?

PS: Working with virtual environments produced with the --system-site-packages option is very convenient when you do not have admin privileges but if any modifications to the base Python make the virtual env buggy, it does not seem to be a good method!

PS: This issue is related to this question virtualenv not finding updated module.

Community
  • 1
  • 1
paugier
  • 1,838
  • 2
  • 20
  • 39

2 Answers2

11

if IPython 2.4 has been installed in the virtualenv and IPython 3.0 has later been installed in the base Python, the old IPython should be removed from the virtual environment and replaced by a copy of the newer package.

You might be able to tweak an existing virtualenv, e.g. by creating a new and copying files into the existing one. However, I find the best and safe way to update is as follows:

# preserve installed packages
source /path/to/venv/bin/activate
pip freeze > requirements.txt
deactivate
# careful now, this destroys all
rm -rf /path/to/venv

Then create a new virtualenv

# apply base changes
virtualenv --system-site-packages /path/to/venv
source /path/to/venv/bin/activate
pip install -r requirements.txt
miraculixx
  • 10,034
  • 2
  • 41
  • 60
  • 4
    I think it might be even simpler than this. I think all you need to do is "virtualenv --system-site-packages /path/to/venv" after the upgrade. Seems to do the trick on my system – yassam Jun 21 '16 at 01:19
  • @yassam `--system-site-packages` gives access to the packages system-wide. If some packages installed in the venv are not installed system-wide, that doesn't work. – Jacques Gaudin Nov 04 '18 at 18:58
0

Just had the same problem and the best answer is deprecated. Therefore, the creation of the virtualenv with python3 should be done like this:

python3 -m venv /path/to/venv

The result would be:

source /path/to/venv/bin/activate
pip3 freeze > requirements.txt
deactivate
rm -rf /path/to/venv
python3 -m venv /path/to/venv
source /path/to/venv/bin/activate
pip3 install -r requirements.txt

keep in mind this is only valid for python 3

azak
  • 481
  • 3
  • 4
  • you don't even need to activate. invoking `bin/python` from the venv's path is sufficient (e.g. `/path/to/venv/bin/python -m pip freeze > requirements.txt`) – cowbert Jan 22 '21 at 21:47