How to reproduce a Python environment with pip replacing the existing environment?

Viewed 171

Python environment has been traditionally reproduced with a requirements.txt file. This works only if you're willing to create a new environment

Reproduce Python Env with a new environment

$ python -m venv .venv && source .venv/bin/activate
$ pip install -r requirements.txt
$ pip list

  pkg1==1.0.0
  pkg2==1.0.0
  pkg2_dep==1.0.0 # Not written in requirement.txt

Reproduce Python Env with an existing environment

$ python -m venv .venv && source .venv/bin/activate
$ pip install requirements.txt

# Made changes to requirements.txt
# Removed pk2==1.0.0
$ pip install requirements.txt
$ pip list

  pkg1==1.0.0
  pkg2==1.0.0 # Should be uninstalled!
  pkg2_dep==1.0.0 # this too

The limitation above is due to pip being unable to install and uninstall together. Other languages support this by using lock files.


Question:

  • How to use pip to reproduce a Python environment with requirements.txt or the new pyproject.toml?
  • If not possible with pip, what other solutions from other packager-manager exists for this purpose?
1 Answers
Related