Home » Learn Python » Getting Started » Python Virtual Environments

Python Virtual Environments

Python virtual environments make it easy to work with multiple versions of Python on the same machine. It’s recommended that you always use a virtual environment to run your code, so that you’re always using the correct version of Python.

Creating a Python Virtual Environment

It’s very important here that the python command you use here runs the correct version of python, usually the most recently installed python. You can check this as follows.

python --version

If this doesn’t give you the correct version, you need to figure out where your python installed. You can try typing python3 or the exact location, e.g. /usr/local/bin/python3.

It’s really important that the python command you use at the next step invokes the correct version of python!

After figuring out how to run the correct version, type the following to create a Python virtual environment (instead of ‘python’, use whatever command invokes the correct version of Python).

python -m venv venv

The first option loads the venv module. The final option specifies that the virtual environment files should be placed in a directory which is also called ‘venv’.

Activating the Python Virtual Environment

After this you need to activate the virtual environment by running one of the scripts in the scripts or bin subdirectory of the venv directory. Which one you run depends on what shell you are using.

If you have problems running the activate script, it may be easiest to install Microsoft Powershell, run Powershell, with pwsh, and then use the Powershell activate script.

$ pwsh
PS /Users/john/projects> ./venv/bin/Activate.ps1

Now, when you type python, you will always get the correct version of Python. When you install packages with pip, the correct packages for your Python version will install.

Leave a Reply

Blog at WordPress.com.

%d bloggers like this: