Python venv (virtual environment) is a tool in Python’s standard library that allows you to create isolated environments for Python projects. It enables you to have separate environments with their own installed packages and dependencies without interfering with each other.
Using virtual environments with venv is considered a best practice when working on Python projects, as it helps manage dependencies and ensures project reproducibility across different environments.
Creating a virtual environment Python Ubuntu
To create a virtual environment for Python in Ubuntu, you can follow these steps:
Step #1: Install python3-venv
sudo apt install python3-venv
Step #2: Create a virtual environment (venv)
python3 -m venv codetryout_venv1
This will create a virtual environment named codetryout_venv1.
Step #3: Activate the virtual environment: (Switching to the new virtual environment)
source codetryout_venv1/bin/activate
You will notice that the prompt in the terminal changes, indicating that you are now inside the virtual environment.
You can now install Python packages or run Python scripts within the virtual environment. For example, you can install packages using pip.
pip install package_name
Replace package_name with the name of the package you want to install.
How to deactivate the virtual environment?
When you’re done working, run:
deactivate
The prompt will return to its normal state.
By creating a virtual environment, you can isolate the Python packages and dependencies specific to your project, making it easier to manage and maintain consistency. Remember to activate the virtual environment whenever you want to work on your project and install packages within the virtual environment to keep them separate from the global Python installation.
Conclusion
Creating a virtual environment using venv creates a directory containing a copy of the Python binary, the standard library, and a few other supporting files. This isolated environment allows you to install and manage packages specific to your project without affecting the system-wide Python installation or other projects.
Related to creating a virtual environment Python
- How to create Virtual Environments Python Windows
- How to Create a Virtual Environment Python Ubuntu
- How to install a module on virtual environment – requests in Python (Windows and Ubuntu)
FAQs
Error: The virtual environment was not created successfully because ensurepip is not available
The virtual environment was not created successfully because ensurepip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command.
apt install python3.8-venv
You may need to use sudo with that command. After installing the python3-venv
package, recreate your virtual environment.
Failing command: ['/home/dev/codetryout_venv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
Solution: Install Ubuntu package python3-venv.