What is virtual environment in Python?
A virtual environment is a tool that helps to keep dependencies required by different projects. By creating an isolated virtual environment, the Python interpreter, libraries and scripts installed into it are isolated from those installed in other virtual environments and any libraries installed in your system.
Why to use virtual environment?
Different projects may have different requirements on the version of the same package. For example, imagine you’re working on two web-based projects one of them uses Djando 4.0 another one uses Djando 4.1. In such scenario, virtual environment can be really useful to manage dependencies of both projects.
How to set up a virtual environment using pipenv?
3 Steps Using pipenv
- 1. Open Terminal. Go to your project folder. Create a virtual environment by using pipenv shell and by telling it which version of python to use
pipenv shell --python /Library/Frameworks/Python.framework/Versions/3.10/bin/python3.10.exe
After this step, you’ll see a Pipfile created in the project folder. A Pipfile is a file that describes out environment and how we can build it back from scratch. It’s a TOML format file that contains keys and values for storing the package source and versions.
- 2. Install the needed packages in this environment.
pipenv install pandas
After this step, a Pipfile.lock is created. This is a file we are not actually meant to change manually. It’s a generated file with more detailed description of our current environment. It contains a deterministic field, that’ll help to give you the exact same environment every time. You only get a different field when you explicitly update the lock file.
- 3. Activate the virtual environment
The virtual environment is automatically activated for you when you do the step 1 & 2. If not, use the same command from step 1.
pipenv shell
Deactivate the virtual environment using the following code.
exit
Reference tutorial: