Python tutorials > Deployment > Virtual Environments > How to create/activate virtual environments?
How to create/activate virtual environments?
Creating a Virtual Environment with venv
venv
module is the standard way to create virtual environments in Python 3.3 and later. The command python3 -m venv myenv
creates a virtual environment in a directory named myenv
. You can replace myenv
with any name you prefer for your environment.venv
module as a script (-m
). The venv
module then sets up the necessary directory structure and files to isolate the Python environment.
python3 -m venv myenv
Activating the Virtual Environment (Linux/macOS)
activate
script located in the environment's bin
directory.(myenv)
), indicating that you are working within the virtual environment.
source myenv/bin/activate
Activating the Virtual Environment (Windows)
Scripts
directory of the virtual environment. You can activate the environment by running the activate
script directly in the command prompt or PowerShell.
myenv\Scripts\activate
Deactivating the Virtual Environment
deactivate
command. This will return you to your system's default Python environment.
deactivate
Concepts Behind Virtual Environments
PATH
environment variable so that Python executables and scripts within the environment are found first. This ensures that you're using the Python interpreter and packages installed within the environment, rather than the system-wide Python installation.
Real-Life Use Case
Best Practices
pip
.requirements.txt
file to track your project's dependencies. This allows you to easily recreate the environment on other machines.
Interview Tip
When to Use Them
Memory Footprint
Alternatives
venv
is the standard, other tools like virtualenv
and conda
can also be used to create virtual environments. conda
is especially popular for data science projects and can manage non-Python dependencies as well. pipenv
is a higher-level tool that manages both virtual environments and dependencies.
Pros
Cons
FAQ
-
What is a
requirements.txt
file?
Arequirements.txt
file is a text file that lists all the Python packages required by a project. It allows you to easily recreate the environment by runningpip install -r requirements.txt
. You can generate this file usingpip freeze > requirements.txt
. -
How do I manage dependencies in my virtual environment?
Usepip
, the Python package installer, to install, upgrade, and uninstall packages within the activated virtual environment. For example:pip install requests
,pip install --upgrade requests
, andpip uninstall requests
. -
Why is my virtual environment not working?
Make sure the virtual environment is activated. Check if the environment's name is shown in your terminal. If not, try activating it again using the appropriate command for your operating system. Also, verify that you've installed packages usingpip
*after* activating the environment.