Python venv: How To Create, Activate, Deactivate, And Delete (2024)

Python virtual environments allow you to install Python packages in an isolated location from the rest of your system instead of installing them system-wide. Let’s look at how to use the Python venv, short for Python virtual environment, also abbreviated as virtualenv.

In this article, you will learn:

  • The advantages of using virtual environments
  • How to create a venv
  • How to activate and deactivate it
  • Different ways to delete or remove a venv
  • How a venv works internally

If you want to learn about virtual environments thoroughly and get some hands-on practice, please have a look at my Python Fundamentals II course. It’s a deep dive into modules, packages, virtual environments, and package managers.

Table of contents

Why you need virtual environments

There are multiple reasons why virtual environments are a good idea, and this is also the reason why I’m telling you about them before we continue to the part where we start installing 3rd party packages. Let’s go over them one by one.

Preventing version conflicts

You could argue that you’re very efficient if you install third-party packages system-wide. After all, you only need to install it once and can use the package from multiple Python projects, saving you precious time and disk space. There’s a problem with this approach that may start to unfold weeks or months later, however.

Suppose your project,Project A, is written against a specific version oflibrary X. In the future, you might need to upgradelibrary X. Say, for example, you need the latest version for another project you started, calledProject B. You upgradelibrary Xto the latest version, andproject Bstarts working fine. Great! But once you did this, it turns out yourProject Acode broke badly. After all, APIs can change significantly on major version upgrades.

A virtual environment fixes this problem by isolating your project from other projects and system-wide packages. You install packages inside this virtual environment, specifically for the project you are working on.

Easy to reproduce and install

Virtual environments make it easy to define and install the packages specific to your project. Using a requirements.txt file, you can define exact version numbers for the required packages to ensure your project will always work with a version tested with your code. This also helps other users of your software since a virtual environment helps others reproduce the exact environment for which your software was built.

Works everywhere, even when not root

If you’re working on a shared host, like those at a university or a web hosting provider, you won’t be able to install system-wide packages since you don’t have the administrator rights to do so. In these places, a virtual environment allows you to install anything you want locally in your project.

Virtual environments vs. other options

There are other options to isolate your project:

  1. In the most extreme case, you could buy a second PC and run your code there. Problem fixed! It was a bit expensive, though!
  2. A virtual machine is a much cheaper option but still requires installing a complete operating system—a bit of a waste as well for most use cases.
  3. Next in line iscontainerization, with the likes of Docker and Kubernetes. These can be very powerful and are a good alternative.

Still, there are many cases when we’re just creating small projects or one-off scripts. Or perhaps you just don’t want to containerize your application. It’s another thing you need to learn and understand, after all. Whatever the reason is, virtual environments are a great way to isolate your project’s dependencies.

How to create a Python venv

There are several ways to create a Python virtual environment, depending on the Python version you are running.

Before you read on, I want to point you to two other tools, Python Poetry and Pipenv. Both these tools combine the functionality of tools that you are about to learn: virtualenv and pip. On top of that, they add several extras, most notably their ability to do proper dependency resolution.

To better understand virtual environments, I recommend you learn the basics first though from this article. I just want to ensure that you know that there are nicer ways to manage your packages, dependencies, and virtual environments.

Python 3.4 and above

If you are running Python 3.4+, you can use the venv module baked into Python:

$ python -m venv [directory]

This command creates a venv in the specified directory and copies pip into it as well. If you’re unsure what to call the directory: venv is a commonly seen option; it doesn’t leave anyone guessing what it is.

A little further in this article, we’ll look closely at the just-created directory. But let’s first look at how to activate this virtual environment.

All other Python versions

The alternative that works for any Python version is using the virtualenv package. You may need to install it first with pip install:

$ pip install virtualenv

Once installed, you can create a virtual environment with:

$ virtualenv [directory]

Python venv activation

How you activate your virtual environment depends on the OS you’re using.

Windows venv activation

To activate your venv on Windows, you need to run a script that gets installed by venv. If you created your venv in a directory called myenv, the command would be:

# In cmd.exevenv\Scripts\activate.bat# In PowerShellvenv\Scripts\Activate.ps1

Linux and MacOS venv activation

On Linux and MacOS, we activate our virtual environment with the source command. If you created your venv in the myvenv directory, the command would be:

$ source myvenv/bin/activate

That’s it! We’re ready to rock! You can now install packages with pip, but I advise you to keep reading to understand the venv better first.

Modules, Packages, And Virtual Environments

My course Python Fundamentals II extensively covers:

  • creating your own modules and packages,
  • Using virtual environments
  • Leveraging Python package managers like Poetry and Pipenv to make your life as a programmer easier.

Advance your productivity as a Python programmer and join my course today!

Buy now for $29 (from $49)

How a Python venv works

When you activate a virtual environment, yourPATHvariable is changed. On Linux and MacOS, you can see it for yourself by printing the path withecho $PATH. On Windows, useecho %PATH% (in cmd.exe) or $Env:Path (in PowerShell). In my case, on Windows, it looks like this:

C:\Users\erik\Dev\venv\Scripts;C:\Program Files\PowerShell\7;C:\Program Files\AdoptOpen....

It’s a big list, and I only showed the beginning of it. As you can see, the Scripts directory of my venv is put in front of everything else, effectively overriding all the system-wide Python software.

So what does this PATH variable do?

When you enter a command that can’t be found in the current working directory, your OS starts looking at all the paths in the PATH variable. It’s the same for Python. When you import a library, Python starts looking in your PATH for library locations. And that’s where our venv-magic happens: if your venv is there in front of all the other paths, the OS will look there first before looking at system-wide directories like /usr/bin. Hence, anything that gets installed in our venv is found first, and that’s how we can override system-wide packages and tools.

What’s inside a venv?

If you take a look inside the directory of your venv, you’ll see something like this on Windows:

.├── Include├── Lib│ └── site-packages├── pyvenv.cfg└── Scripts ├── activate ├── activate.bat ├── Activate.ps1 ├── deactivate.bat ├── pip3.10.exe ├── pip3.exe ├── pip.exe ├── python.exe └── pythonw.exe

And on Linux and MacOS:

Python venv: How To Create, Activate, Deactivate, And Delete (2)

You can see that:

  • The Python command is made available both aspythonandpython3(on Linux and MacOS), and the version is pinned to the version with which you created the venv by creating a symlink to it.
  • On Windows, the Python binary is copied over to the scripts directory.
  • All packages you install end up in the site-packages directory.
  • We have activation scripts for multiple shell types (bash, csh, fish, PowerShell)
  • Pip is available under the names pip and pip3, and even more specifically under the namepip3.7because I had a Python 3.7 installation at the time of writing this.

Deactivate the Python venv

Once you have finished working on your project, it’s a good habit to deactivate its venv. By deactivating, you basically leave the virtual environment. Without deactivating your venv, all other Python code you execute, even if it is outside your project directory, will also run inside of the venv.

Luckily, deactivating your virtual environment couldn’t be simpler. Just enter this:deactivate. It works the same on all operating systems.

Deleting a Python venv

You can completely remove a virtual environment, but how you do that depends on what you used to create the venv. Let’s look at the most common options.

Delete a venv created with Virtualenv or python -m venv

There’s no special command to delete a virtual environment if you used virtualenv or python -m venv to create your virtual environment, as is demonstrated in this article. When creating the virtualenv, you gave it a directory to create this environment in.

If you want to delete this virtualenv, deactivate it first and then remove the directory with all its content. On Unix-like systems and in Windows Powershell, you would do something like:

$ deactivate# If your virtual environment is in a directory called 'venv':$ rm -r venv

Delete a venv with Pipenv

If you used Pipenv to create the venv, it’s a lot easier. You can use the following command to delete the current venv:

pipenv --rm

Make sure you are inside the project directory. In other words, the directory where the Pipenv and Pipenv.lock files reside. This way, pipenv knows which virtual environment it has to delete.

If this doesn’t work, you can get a little nastier and manually remove the venv. First, ask pipenv where the actual virtualenv is located with the following command:

$ pipenv --env/home/username/.local/share/virtualenvs/yourproject-IogVUtsM

It will output the path to the virtual environment and all of its files and look similar to the example above. The next step is to remove that entire directory, and you’re done.

Delete a venv with Poetry

If you created the virtualenv with Poetry, you can list the available venvs with the following command:

poetry env list

You’ll get a list like this:

test-O3eWbxRl-py2.7test-O3eWbxRl-py3.6test-O3eWbxRl-py3.7 (Activated)

You can remove the environment you want with the poetry env remove command. You need to specify the exact name from the output above, for example:

poetry env remove test-O3eWbxRl-py3.7

Conclusion

You learned how to create, activate, deactivate, and delete virtual environments. We also looked behind the curtains to see why and how a venv works. Now that you know how to create a venv, you need to learn how to install packages inside of it. After that, I strongly recommend you to learn about Pipenv or Poetry. These tools combine the management of your virtual environment with proper package and dependency management.

Keep learning

  • Next up: how to install packages with pip inside your venv
  • Pipenv is a better way of managing your venv and packages.
  • Learn the most common Linux commands (like cd, mkdir, pwd, etcetera)
  • Official venv documentation: If you want to know all the details and command-line options

Are you enjoying this free tutorial? Please also have a look at my premium courses. They offer a superior user experience with small, easy-to-digest lessons and topics, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

Python venv: How To Create, Activate, Deactivate, And Delete (2024)

FAQs

How do I deactivate a VENV? ›

You can deactivate a virtual environment by typing “deactivate” in your shell. The exact mechanism is platform-specific and is an internal implementation detail (typically a script or shell function will be used).

Do I have to activate VENV every time? ›

You don't specifically need to activate an environment; activation just prepends the virtual environment's binary directory to your path, so that “python” invokes the virtual environment's Python interpreter and you can run installed scripts without having to use their full path.

How do I reset my VENV Python? ›

Use a Bash console to enter the commands.
  1. 1) Use a requirements. txt file to record what packages you're using. ...
  2. 2) Remove your old virtualenv. Using plain virtualenvs: rm -rf /home/myusername/path/to/virtualenv. ...
  3. 3) Create a new virtualenv. ...
  4. 4) Reinstall your packages. ...
  5. 5) Restart your web app. ...
  6. 6) All done!

How do I know if VENV is activated? ›

Once you can see the name of your virtual environment—in this case (venv) —in your command prompt, then you know that your virtual environment is active. You're all set and ready to install your external packages!

How do I start VENV? ›

Create a Virtual Environment using “virtualenv”
  1. Install the virtualenv. ...
  2. Create a virtual environment. ...
  3. Create an environment with a specific version of Python. ...
  4. Activate the virtual environment. ...
  5. Deactivate the virtual environment. ...
  6. Check which Environment you are in. ...
  7. Remove an environment.
22 Mar 2020

How do you clear an environment in Python? ›

The os module in Python provides functions that help us interact with the underlying operating system. The unsetenv() method is used to delete the given environment variable.

How do you activate VS code on VENV? ›

VSCode Setup
  1. Update Venv Path Settings in VSCode. Open VSCode preferences ( Ctrl + , ) and search for “venv”. Add ~/.virtualenvs to the “Venv Path” settings, like so: ...
  2. Add the Virtual Environment Folder to VSCode. Add the folder that contains the virtual environment to VSCode, in our case, it is the ~/. virtualenv folder.
3 Dec 2020

How do I delete a virtual environment in PyCharm? ›

You can clean out old PyCharm interpreters that are no longer associated with a project via Settings -> Project Interpreter, click on the gear in the top right, then click "More". This gives you a listing where you can get rid of old virtualenvs that PyCharm thinks are still around.

What happens if you don't deactivate venv? ›

Once you have finished working on your project, it's a good habit to deactivate its venv. By deactivating, you basically leave the virtual environment. Without deactivating your venv, all other Python code you execute, even if it is outside your project directory, will also run inside of the venv.

Should I use venv or virtualenv? ›

These are almost completely interchangeable, the difference being that virtualenv supports older python versions and has a few more minor unique features, while venv is in the standard library.

Do virtual environments take up space? ›

Mmm, virtual environments are somehow a waste of disk space because they are meant to create isolated environments that have -almost- no dependencies outside themselves.

Where is venv stored? ›

Where to store virtual environments?
  1. Have one global place for them, like ~/virtualenvs .
  2. Store them in each project's directory, like ~/git/foobar/. venv .
4 Sept 2018

How do you freeze requirements? ›

The most common command is pip freeze > requirements. txt , which records an environment's current package list into requirements. txt. If you want to install the dependencies in a virtual environment, create and activate that environment first, then use the Install from requirements.

How do I activate venv in PyCharm? ›

Set value of PyCharm (4.0. 1) File > Settings > Tools > Terminal > Shell path to /bin/bash --rcfile ~/pycharmactivate.
...
Just do:
  1. enter in your terminal venv directory( cd venv/Scripts/ )
  2. You will see activate. bat.
  3. Just enter activate. bat in your terminal after this you will see YOUR ( venv )

How do I enable VENV Windows? ›

If you're using Windows, use the command "venv\Scripts\activate" (without the word source) to activate the virtual environment. If you're using PowerShell, you might need to capitalize Activate.

How do I set an environment variable in Python? ›

To permanently modify the default environment variables, click Start and search for 'edit environment variables', or open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you can add or modify User and System variables.

How do you check the current virtual environment in Python? ›

The name of the current virtual environment will now appear on the left of the prompt (e.g. (venv)Your-Computer:project_folder UserName$ ) to let you know that it's active. From now on, any package that you install using pip will be placed in the venv folder, isolated from the global Python installation.

How do I activate environment in terminal? ›

Use the terminal or an Anaconda Prompt for the following steps:
  1. Create the environment from the environment.yml file: conda env create -f environment. yml. ...
  2. Activate the new environment: conda activate myenv.
  3. Verify that the new environment was installed correctly: conda env list.

What is VENV in Python? ›

The module used to create and manage virtual environments is called venv . venv will usually install the most recent version of Python that you have available. If you have multiple versions of Python on your system, you can select a specific Python version by running python3 or whichever version you want.

How do I install a VENV module? ›

How to install virtualenv:
  1. Install pip first. sudo apt-get install python3-pip.
  2. Then install virtualenv using pip3. ...
  3. Now create a virtual environment. ...
  4. You can also use a Python interpreter of your choice. ...
  5. Active your virtual environment: ...
  6. Using fish shell: ...
  7. To deactivate: ...
  8. Create virtualenv using Python3.

How do I enable VENV on Windows? ›

If you're using Windows, use the command "venv\Scripts\activate" (without the word source) to activate the virtual environment. If you're using PowerShell, you might need to capitalize Activate.

Which command is used to activate virtual environment after creating it? ›

Using virtualenv

After running this command, a directory named my_name will be created. This is the directory which contains all the necessary executables to use the packages that a Python project would need. This is where Python packages will be installed.

How do you activate VS code on VENV? ›

VSCode Setup
  1. Update Venv Path Settings in VSCode. Open VSCode preferences ( Ctrl + , ) and search for “venv”. Add ~/.virtualenvs to the “Venv Path” settings, like so: ...
  2. Add the Virtual Environment Folder to VSCode. Add the folder that contains the virtual environment to VSCode, in our case, it is the ~/. virtualenv folder.
3 Dec 2020

How do I activate VENV in PyCharm? ›

Set value of PyCharm (4.0. 1) File > Settings > Tools > Terminal > Shell path to /bin/bash --rcfile ~/pycharmactivate.
...
Just do:
  1. enter in your terminal venv directory( cd venv/Scripts/ )
  2. You will see activate. bat.
  3. Just enter activate. bat in your terminal after this you will see YOUR ( venv )

Should I use VENV or virtualenv? ›

These are almost completely interchangeable, the difference being that virtualenv supports older python versions and has a few more minor unique features, while venv is in the standard library.

How do I set an environment variable in Python? ›

To permanently modify the default environment variables, click Start and search for 'edit environment variables', or open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you can add or modify User and System variables.

How do I install a VENV module? ›

How to install virtualenv:
  1. Install pip first. sudo apt-get install python3-pip.
  2. Then install virtualenv using pip3. ...
  3. Now create a virtual environment. ...
  4. You can also use a Python interpreter of your choice. ...
  5. Active your virtual environment: ...
  6. Using fish shell: ...
  7. To deactivate: ...
  8. Create virtualenv using Python3.

How do I create a virtual environment in Python Windows 10? ›

There are four basic steps to install a virtual environment on windows: Install Python. Install Pip. Install VirtualEnv.
...
Additionally, the sudo command may be needed if not running as the root user.
  1. Install Python. Python 3.8. ...
  2. Install PIP. ...
  3. Install Virtualenv. ...
  4. Install VirtualEnvWrapper-win.
18 Sept 2020

What is VENV in Python? ›

The module used to create and manage virtual environments is called venv . venv will usually install the most recent version of Python that you have available. If you have multiple versions of Python on your system, you can select a specific Python version by running python3 or whichever version you want.

Why do I need a Python virtual environment? ›

virtualenv is used to manage Python packages for different projects. Using virtualenv allows you to avoid installing Python packages globally which could break system tools or other projects.

How do I turn off VS code on VENV? ›

ACTIVATE\DEACTIVATE VSCODE PYTHON VENV IN UNDER 90 SEC

How do I disable code in Python? ›

both of which require me to manipulate every line I want to deactivate.
...
Here are several ways which you can use:
  1. Move the code into a function/method. ...
  2. Move the code to a new function in a new module. ...
  3. Create a config flag and protect the code with an if . ...
  4. Move all your code into a class.
29 Jan 2016

How do I get out of VENV in Vscode? ›

Exiting from the virtualenv

You can exit from the virtualenv using exit command, or by pressing Ctrl+d.

How do I run VENV in Python? ›

Outline
  1. Open a terminal.
  2. Setup the pip package manager.
  3. Install the virtualenv package.
  4. Create the virtual environment.
  5. Activate the virtual environment.
  6. Deactivate the virtual environment.
  7. Optional: Make the virtual environment your default Python.
  8. More: Python virtualenv documentation.
26 Nov 2014

How do I delete a virtual environment in PyCharm? ›

You can clean out old PyCharm interpreters that are no longer associated with a project via Settings -> Project Interpreter, click on the gear in the top right, then click "More". This gives you a listing where you can get rid of old virtualenvs that PyCharm thinks are still around.

How do I set environment variables in PyCharm? ›

env (and . flaskenv) file in the pycharm flask/django console.
...
  1. Tools > Terminal > Environment variables.
  2. Languages & Frameworks > Django > Environment variables.
  3. Build, Execution, Deployment > Console > Python Console > Environment variables.
  4. Build, Execution, Deployment > Console > Django Console > Environment variables.

Top Articles
Latest Posts
Article information

Author: Van Hayes

Last Updated:

Views: 5845

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.