How to create virtual environment in Python (venv and virtualenv)
In the following article, we'll look at virtual environments in Python using two prominent tools: venv and virtualenv. Virtual environments are vital to Python developers considering they offer a clean and segregated environment for their projects, preventing dependency conflicts and ensuring the project's installation of packages.
By setting up a virtual environment in Python, you may create an exclusive area where you can install Python packages and dependencies unique to your project without interfering with other projects or the system-level Python installation.
1. Creating a Virtual Environment using venv
The actions to construct a virtual environment with venv in Python are as follows:
- On your computer, launch the terminal or command prompt. Go to the directory where the virtual environment is to be created. To switch directories, use the cd command. For instance, if your directory name is "pythonenv," then type cd pythonenv or not, then create a new directory and press Enter to establish the virtual environment in the pythonenv directory.
- If you want to build a virtual environment with the name "env" use the following command on your terminal after you have entered the relevant directory: python -m venv env . Keep in mind that "env" is only one possible name for your virtual environment; you may select whatever name you choose. Hit Enter, then watch as the virtual world is constructed. It can take a few seconds.
- By using the following command in Mac or Linux, you may activate the virtual environment: source env/bin/activate
- In Windows above command not working to activate your environment then use the following command to turn on or activate the virtual environment after you've reached the desired directory: \env\Scripts\activate
- In Gitbash, activate virtual environment: source "F:\python\env\Scripts\activate"
- Replace this path to paste your env activate file location full path.
2. Creating a Virtual Environment using virtualenv
The actions to construct a virtual environment with virtualenv in Python are as follows:
- On your computer, launch the terminal or command prompt. Firstly, install the virtualenv in your terminal type pip install virtualenv, and hit enter.
- If you want to build a virtual environment with the name "env" use the following command on your terminal after you have entered the relevant directory: virtualenv env
- By using the following command in Mac or Linux, you may activate the virtual environment: source env/bin/activate
- In Windows, above command not working to activate your environment then use the following command to turn on or activate the virtual environment after you've reached the desired directory: \env\Scripts\activate
- In Gitbash, activate the virtual environment: source "F:\python\env\Scripts\activate" Replace this path to paste your env activate file location full path.