Python: How to create a virtual environment
A virtual environment is a self-contained directory that holds a Python interpreter and its associated libraries. It allows you to isolate…
A virtual environment is a self-contained directory that holds a Python interpreter and its associated libraries. It allows you to isolate your project’s dependencies from the system-wide Python installation, making it easier to manage different projects with different requirements.
Step 1: Install virtualenv
If you don’t have virtualenv installed, you can install it using pip, Python's package manager:
pip install virtualenvStep 2: Create a Virtual Environment
Create a new directory for your project and navigate to it in your terminal:
mkdir my_project
cd my_projectCreate a virtual environment in the project directory:
virtualenv venvThis will create a directory named venv in your project folder, which will hold the virtual environment.
Step 3: Activate the Virtual Environment
- On Windows:
venv\Scripts\activate- On macOS and Linux:
source venv/bin/activateYou’ll notice that your command prompt changes to indicate that the virtual environment is active. This means that any Python-related commands you run will use the Python interpreter and libraries within the virtual environment.
Step 4: Installing Packages
With the virtual environment active, you can install packages just like you would with the system-wide Python installation. For example, let’s install the requests package:
pip install requestsThis package will be installed only within the virtual environment, keeping your system-wide Python environment clean.
Step 5: Using the Virtual Environment
You can now work on your project within the virtual environment. Create your Python files, install dependencies, and run your scripts just like you normally would.
Step 6: Deactivate the Virtual Environment
When you’re done working on your project, you can deactivate the virtual environment:
deactivateThis returns you to your system’s global Python environment.
Conclusion
Using virtual environments is a recommended practice when working on Python projects. It helps you manage dependencies, avoid conflicts, and keep your project’s environment isolated. By following this tutorial, you should now be able to create and use virtual environments for your Python projects.