How do I venv a new environment that I can then copy to anywhere and the environment is brand new.
The current known solution is to modify the activate file, but how should I do that?
It’s best to create a new venv in the new location, not copy one. If the requirement is to install the same dependencies in this venv, then a simple requirements.txt file will suffice.
To make a portable venv, I believe the parent Python installation also needs to be portable.
Otherwise, run almost anywhere portability can easily be achieved via a Docker image. This can easily be based on an official Python image.
thank you for reply.
I’d like to ask a question.
Is it possible to docker add .env
if you want to
If it’s not feasible, I still need to implement this requirement
Because in our company the old environment is installed and portable. This can be done by copy
or rsync
. But the employee who did this has left. I would like to understand how this is achieved.
As far as I know, a virtual environment is specific to:
- absolute path on disk
- although it seems to be relatively easy to modify if you know what files to modify
- Python implementation (example: CPython vs. PyPy)
- Python version (example: 3.11 vs. 3.12)
- operating system (example: Linux vs Windows
- CPU bitness (example: 32 bits vs. 64 bits)
- maybe something else I am forgetting
If all these things are exactly the same – as can be the case with containers – then it could be possible to reuse the same virtual environment.
Typically if all dependencies are pure Python, then it could be that only the path matters. It is more complicated than this of course because of dependency constraints where one dependency is necessary only on some environment (think importlib_resources
for example).
Figure out the steps to build the venv from scratch, and write those down in the Dockerfile. When building an image from the Dockerfile, Docker will build the Python venv for you inside it.
There’s a fair bit to Docker, but it can be as simple as adding a one line shell command after RUN
, and learning the basics is a far more valuable use of your time than copying and pasting olf Python virtual environments that by design should be deleted and rebuilt, not moved.
My suggestion is to make a batch/shell file which does the following steps when you want a new project with the same environment as another one:
- Make the subdirectory.
- Go to the subdirectory.
- Make the new environment.
- Activate the new environment.
- Use pip to install all modules you want in there.
To see all the modules in your current project do these steps:
- Go to the project.
- Activate that project’s environment.
- At the command line for the OS type
pip freeze > modules.txt
. This will list all modules and save them in the text file called “modules.txt”.