Skip to content

Instantly share code, notes, and snippets.

@purarue
Last active November 16, 2024 05:33
Show Gist options
  • Save purarue/9a3fa70d377e5489e962334242602f50 to your computer and use it in GitHub Desktop.
Save purarue/9a3fa70d377e5489e962334242602f50 to your computer and use it in GitHub Desktop.
Copying dependencies to a new virtual environment
# activate it
source bin/env/bin/activate
# make sure python is pointing at the correct place
# (it should be inside the .venv folder which youre activated in)
(.venv) [dev@fish-webserver ~/code/dbsentinel/.venv ] $ which python3
/home/dev/code/dbsentinel/.venv/bin/python3
(.venv) [dev@fish-webserver ~/code/dbsentinel/.venv ] $ which pip3
/home/dev/code/dbsentinel/.venv/bin/pip3
(.venv) [dev@fish-webserver ~/code/dbsentinel/.venv ] $ which pip
/home/dev/code/dbsentinel/.venv/bin/pip
# if you look inside the bin folder you'll actually
# see all the aliases that its setup at the front of
# your $PATH, these links override anything else
# you have run system wide, that's what
# the source bin/env/bin/activate does when
# you source the shell file
$ ls bin/env/bin
python
python3
pip3
pip
....
....
# so then, since you know pip is using your internal pip
# you can make a frozen requirements file:
pip freeze --local >reqs.txt
cat reqs.txt # just look at the output
# (MAKE SURE YOU SAVE THE reqs.txt FILE, you need that)
# now, you can remove the venv, (or just move it elsewhere in case
# this fails)
mv bin/env bin/backup_env
# leave the old venv
deactivate
# make a new one with the python version you want
# if you have it installed globally, you can use
# $(which python3) to get the path, would be something like
# if you dont have virtualenv installed, `pip install virtualenv`
virtualenv -p "$(which python3.12)" bin/env
# or if using pyenv or something
virtualenv -p "$(pyenv root)/versions/3.10.1/bin/python" bin/env
# if you can't find virtualenv on your $PATH, you can always
# use the 'python3 -m' prefix to make sure it finds the module,
# so you can do:
# python3 -m pip install virtualenv
# python3 -m virtualenv -p "$(which python3.12)" bin/env ...
# using 'python3 -m' before modules is a common way to get
# around $PATH misconfiguration issues.
# activate the new virtualenv
source bin/env/bin/activate
# make sure it doesnt have your old packages there
# (this should print nothing or just a couple packages)
pip freeze
# then, use the reqs.txt file to install stuff using
# the -r flag:
pip install -r ./reqs.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment