Python Virtual Environment 101
February 11 2024 by Naufal Rafiawan BasaraWhat is python virtual environment?
A Python Virtual Environment is an isolated space where you can work on your Python projects, separately from your system-installed Python. A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated Python virtual environments for them. This is one of the most important tools that most Python developers use.
Steps to create python virtual environment
-
Making sure the python already installed in your computer
-
How to check?
Go to terminal and type
python --version
Python 3.11.3
→ (Example of output, which is the version of python installed in your computer) -
What if it doesn’t exist? or the output is not the same?
-
Install through the official python website and select based on your computer operating system (OS)
-
Install through package manager, like brew:
brew install python
-
-
-
Go to spesific working directory (optional)
-
Create new virtual environmetn by open terminal and type
python3 -m venv venv
Now your directory structure will be having new directory named ‘venv’.
-
Activate or deactivate virtual environment
-
Activate virtual environment
on MacOS or Linux
source venv/bin/activate
on Windows OS
venv/Scripts/activate
You will see the name of your virtual environment (venv) before the terminal prompt symbol.
$
→(venv) $
which means the virtual environment is activated. -
Deactivate virtual environment
deactivate
(venv) $
→$
which means the virtual environment is deactivated.
-
-
Virtual environment is active, you can install any library and package dependencies related to the current project by using
pip install package-name