Using a virtual environment for Project dev in Python is a good practice. venv is module that is available since Python 3.3. It can help us to manage the virtual environment in a simple way.
Manage virtual env#
Create a virtual env#
Normally, we create a virtual environment under the project root directory:
python -m venv paht/to/project-root/venvThe name we give to this virtual env is venv.
Under the directory venv, there are different files and folders.
Under my macOS system, it has the following files:
bin/ include/ lib/ pyvenv.cfgActivate and de-activate#
To activate the virtual environment, run this command:
source venv/bin/activateThen your shell prompt changes and tells you are now in the virtual environment.
When the environment has been activated, the VIRTUAL_ENV env variable is set to the path of the environment.
To deactivate the virtual environment, just run deactivate.
ref:
- Python venv: https://docs.python.org/3/library/venv.html
- use venv in Linux: https://www.youtube.com/watch?v=Kg1Yvry_Ydk
Make jupyter work with virtual env#
First, we need to install the ipykernel package inside the virtual env:
pip install ipykernelThen we can generate a kernelspec for jupyter:
python -m ipykernel install --user --name <spec-name>
# output: Installed kernelspec venv in /Users/<your-user-name>/Library/Jupyter/kernels/<spec-name>Now we can open the notebook:
jupyter notebook <your-notebook-name>.ipynbIn the opened browser tab for jupyter,
we can click the Kernel menu and click change kernel to switch the kernel.
Kernelspec management#
To list your kernelspecs:
jupyter kernelspec listTo remove the virtual env spec:
jupyter kernelspec remove <spec-name>ref: