Skip to content

Python

Virtual Environments

Create virtual environment

I use a custom function in PowerShell for creating virtual environments. However, this is only valid for my personal PowerShell profile and won't work outside it. It's really just a shortcut to run the actual code anyway.

PowerShell
1
createvenv

All this really does is run the actual terminal command, as seen in the "Terminal command" tab.

PowerShell
1
python -m venv venv

The first venv is the name of your virtual environment. The second venv is the directory. I generally create virtual environments in a project's root folder, where I want the directory to be located.

Activate virtual environment

Similar to creating a virtual environment, I have a custom PowerShell function that I use to activate virtual environments.

PowerShell
1
venv

Like with the createvenv PowerShell function, this is really just a shortcut for the terminal command.

PowerShell
1
venv\Scripts\activate

The venv is the name of the directory where the virtual environment is located relative to the current directory in the terminal.

Deactivate virtual environment

Deactivating a virtual environment is easy and requires no special shortcut. You simply run:

PowerShell
1
deactivate

While the virtual environment is active, of course.

pip

pip is the package installer for Python that's run through a terminal.

Freeze & install requirements

pip makes it very easy to handle requirements for a Python project by "freezing" them and then "installing" them. This is very helpful for virtual environments.

To "freeze" a project's packages:

PowerShell
1
pip freeze > requirements.txt

And then, when a project has a requirements.txt included, installing the packages is as easy as:

PowerShell
1
pip install -r requirements.txt