Create python virtual environment

With Pip

$ python3 -m venv venv

# Activate environment
$ source venv/bin/activate # for mac users
$ venv\Scripts\activate.bat # for windows users

With Poetry

$ poetry init

$ poetry add DEPENDENCY_NAME

pyproject.toml file example:

pyproject.toml
[tool.poetry]
name = "project name"
version = "0.1.0"
description = "Project description"
authors = ["Your Name"]

[tool.poetry.dependencies]
python = "^3.10"
# Other project dependencies will go here

[tool.poetry.dev-dependencies]
# Development dependencies will go here

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

How to use

Using Pip

1

Create virtual environment

Inside your project folder, create a virtual environment with the following command:

$ python3 -m venv venv

Then, activate the environment:

$ source venv/bin/activate # for mac users
$ venv\Scripts\activate.bat # for windows users

Using Poetry

2

Initialize a poetry project

$ poetry init

This will create a new pyproject.toml file inside your project root.

3

Install dependencies

Run:

$ poetry add DEPENDENCY_NAME

This will activate your virtual environment if exists or create a new one if it doesn't.

To install a development package you can use the --dev or -D flags.

The next time you start the project, you can run poetry shell to activate your project virtual env. To deactivate the environment run deactivate.

In VScode, remember to activate the python interpreter as follows:

$ poetry env info -p

Return to all snippets