Skip to main content
  1. Posts/

Using Virutal Environment in Python with venv

·254 words·2 mins·
Python
Table of Contents

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/venv

The 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.cfg

Activate and de-activate
#

To activate the virtual environment, run this command:

source venv/bin/activate

Then 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:

Make jupyter work with virtual env
#

First, we need to install the ipykernel package inside the virtual env:

pip install ipykernel

Then 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>.ipynb

In 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 list

To remove the virtual env spec:

jupyter kernelspec remove <spec-name>

ref:

Related

Run the Job Immediately after Starting Scheduler in Python APScheduler
·322 words·2 mins
Python APScheduler
Retry for Google Cloud Client
·197 words·1 min
Python GCP
Make Python logging Work in GCP
·570 words·3 mins
Python Logging GCP