Managing Python projects can become tricky when different projects require different versions of libraries or dependencies. A great solution to this problem is using virtual environments. Python's built-in venv module makes it simple to create and manage isolated environments for the projects. This tutorial demonstrates how to create a virtual environment in Python using venv module.
First, create a dedicated directory for the project and navigate into it. You can do this using the following command:
mkdir myproject && cd myproject
Now, create a virtual environment within the project directory using the venv module:
python -m venv venv
python3 -m venv venv
This will create a directory named venv
inside the project directory. This directory contains the Python executable and the pip tool.
Once the virtual environment is created, you need to activate it. The method of activation depends on the operating system:
venv\Scripts\activate.bat
source venv/bin/activate
After activation, the terminal prompt will change, showing the virtual environment's name (e.g., (venv)
), indicating the environment is active. For example:
(venv) adminer@ubuntu:~/myproject$
With the virtual environment activated, you can now install project-specific dependencies using pip. For example:
pip install numpy
When you're done working, deactivate the virtual environment by simply typing:
deactivate
Leave a Comment
Cancel reply