Python virtual environments allow you to install Python packages in a location isolated from the rest of your system, rather than installing them system-wide. Let's see how to use Python venv, short for Python Virtual Environment, also abbreviated asvirtual environment.
In this article you will learn:
- The benefits of using virtual environments
- How to create a venv
- How to enable and disable
- Different ways to delete or delete a venv
- How a venv works internally
If you have some free time, think of mine.Python II Foundation Courseto learn more about virtual environments and practice in the real world. It's a deep dive into modules, packages, virtual environments and package managers.
Index
- 1 Why you need virtual environments
- 2 Virtual Environments vs. Other Options
- 3 How to create a Python Venv
- 4 Activation of Python venv
- How a python venv works
- 6 Disable Python venv
- 7 Removing a venv from Python
- 8 Conclusion
- 9 Keep learning
Why you need virtual environments
There are several reasons why virtual environments are a good idea, which is why I'll talk about them before moving on to the part where we start installing third-party packages. Let's examine them one by one.
Avoiding version conflicts
One could argue that installing third-party packages system-wide is very efficient. After all, you only have to install it once and you can use the package for multiple Python projects, saving you time and disk space. However, there is a problem with this approach that only begins to unravel weeks or months later.
Suppose your projectProject A
, is written in a specific version ofLibrary X
. In the future you may need to update the X library. For example, let's say you need the latest version for another project you started, called project B. You update the X library to the latest version, and project B works fine. Excellent! But once you did, it turned out to be youProject A
the code broke badly. Finally, APIs can change significantly in major version updates.
A virtual environment solves this problem by isolating your project from other projects and packages throughout the system. Within this virtual environment, you install packages specific to the project you are working on.
Easy to play and install
Virtual environments make it easy to define and install packages specific to your project. using aRequirements.txtfile you can define exact version numbers for the packages you need to ensure that your project always works with a tested version of your code. This also helps other users of your software as a virtual environment helps others to replicate the exact environment your software was designed for.
Works everywhere, even if you are not an administrator (root).
If you are working on a shared host, e.g. For example, at a university or web hosting provider, you cannot install system-wide packages because you do not have administrator rights to do so. In these places you can install everything you want locally in your project in a virtual environment.
Virtual environments versus other options
There are other ways to isolate your project:
- In the most extreme case, you can buy a second PC and run your code on it. Problem solved! Although it was a bit expensive!
- A virtual machine is a much cheaper option, but it still requires a full operating system to be installed, which is also wasteful for most use cases.
- Next comes containerization like Docker and Kubernetes. These can be very powerful and are a good alternative.
However, there are many cases where we only create small one-off projects or scripts. Or maybe you just don't want to containerize your app. After all, it's something else that you need to learn and understand. Whatever the reason, virtual environments are a great way to isolate your project's dependencies.
How to create a Python Venv
Depending on the version of Python you're running, there are several ways to create a Python virtual environment.
Before I continue reading, I would like to point out two more tools,Python PoetrymiPipenv. Both tools combine the functionality of the tools you're about to learn: virtualenv and pip. They also add a number of extras, most notably the ability to do proper dependency resolution.
To get a better understanding of virtual environments, I recommend that you first familiarize yourself with the basics with the help of this article. I just want to make sure you know there are better ways to manage your packages, dependencies, and virtual environments.
Python 3.4 or higher
If you're running Python 3.4+, you can use Python's built-in venv module:
python -m venv <directory>
This command creates a venv in the specified directory and also copies pip there. If you are not sure how to access the directory:venv
is a commonly seen option; it leaves no one guessing what it is. So the command in this case would be:
python -m venv venv
A little later in this article, we'll take a closer look at the newly created directory. But first, let's see how to activate this virtual environment.
All other versions of Python
The alternative, which works for any version of Python, is to use the virtualenv package. You may need to install it with firstInstall pipe:
pip install virtualenv
After installation you can create a virtual environment with:
virtualenv [directory]
Python venv activation
How you activate your virtual environment depends on the operating system you use.
Windows activation sale
To activate your venv on windows you need to run a script installed by venv. If you put your venv in a directory calledmienv
, the command would be:
# Em cmd.exevenv\Scripts\activate.bat# Em PowerShellvenv\Scripts\Activate.ps1
Venv activation for Linux and MacOS
On Linux and MacOS we activate our virtual environment with the source command. If you created your venv inmivenv
directory would be the command:
$ source myvenv/bin/activate
Is this! We're ready to rock! now you caninstall packages with pip, but I advise you to continue reading to understand better, come first.
Modules, packages and virtual environments
my courseI give the basics of Python IIlargely covers:
- Createmodules and packages
- Usevirtual environments
- Use of Pythonpackage managerlike Poetry and Pipenv to make your life as a programmer easier.
Increase your productivity as a Python programmer and join my course today!
Buy it now for $9.95 (From $59.95)
How a python venv works
When you activate a virtual environment, yourCAMINO
variable is changed. Under Linux and MacOS you can see for yourself by printing the path with itecho $PATH
. Sin Windows, useecho %PATH%
(in cmd.exe) y$send:path
(in PowerShell). For me it looks like this on Windows:
C:\Users\erik\Dev\venv\Scripts;C:\Programs\PowerShell\7;C:\Programs\AdoptOpen....
It's a long list and I've only shown the beginning. As you can see, my venv places the Scripts directory before anything else, effectively replacing all Python software for the entire system.
So what does this PATH variable do?
If you enter a command that cannot be found in the current working directory, your operating system will start looking for all paths in the PATH variable. The same applies to Python. When you import a library, Python starts looking in your PATH for the library locations. And this is where our venv magic happens: if your venv is before all other paths, the operating system will look there first, before looking in system-wide directories like/usr/bin
. So everything that gets installed in our venv is found first, and that's how we can replace system-wide packages and tools.
What's in a Venv?
If you take a look in your venv directory you will see something like this on Windows:
... pip3.10.exe ├── pip3.exe ├── pip.exe ├── python.exe └── pythonw.exe
And on Linux and MacOS:

You can see this:
- The python command is available as python and python3 (on Linux and MacOS) and the version is set to the version you used to build the venv by symbolically linking it.
- On Windows, the Python binary is copied to the scripts directory.
- All packages you install end up in the site's packages directory.
- We have activation scripts for different shell types (bash, csh, fish, PowerShell)
- Pip is available under pip and pip3, and more specifically under the name
Pip3.7
because at the time of writing I had a Python 3.7 installation.
Disable Python venv
After you've finished working on your project, it's a good habit to clean your venv. By deactivating you leave the virtual environment. Without disabling your venv, any other Python code you run, even if it's outside of your project directory, will also run in your venv.
Luckily, dismantling your virtual environment couldn't be easier. Just write this:deactivate
. It works the same on all operating systems.
Delete a venv from Python
You can remove a virtual environment entirely, but how you do it 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 is no special command to remove a virtual environment if you have used onevirtual environment
Öpython -m venv
to create your virtual environment as shown in this article. When you created virtualenv, you provided a directory to create this environment.
If you want to remove this virtual environment,deactivatefirst and then delete the directory with all its contents. On Unix-like systems and Windows Powershell you would do something like this:
deactivate# If your virtual environment is in a directory named 'venv': rm -r venv
Delete a venv with pipenv
if you usedPipenvto create the venv is much easier. You can use the following command to remove the current venv:
pipenv --rm
Make sure you are in the project directory. In other words, the directory in which thePipenv
mipipenv.lock
files lie. This way pipenv knows which virtual environment to remove.
If that doesn't work, you can get a little meaner and remove the venv manually. First, ask pipenv where the actual virtual environment is with the following command:
pipenv --env/home/username/.local/share/virtualenvs/yourproject-IogVUtsM
It shows the path to the virtual environment and all its files and looks similar to the previous example. The next step is to remove the entire directory and you are done.
Erase a venv with poetry
If you created the virtual environment withPoems, you can list the available venvs with the following command:
List of poetic settings
You will get a list like this:
test-O3eWbxRl-py2.7test-O3eWbxRl-py3.6test-O3eWbxRl-py3.7 (Activado)
You can delete any environment you want withEnv Poem Remover
Domain. You must provide the exact name of the output above, for example:
poesia env eliminar test-O3eWbxRl-py3.7
Diploma
You have learned how to create, activate, deactivate and delete virtual environments. We also look behind the scenes to see why and how a venv works. Now that you know how to create a Venv, you need to learn ithow to install packagesAfter that, I strongly encourage you to read up on itPipenvor poetry. These tools combine managing your virtual environment with proper package and dependency management.
keep learning
- Next:How do I install packages with pip?in your room
- PipenvIt's a better way to manage your sales and packages.
- learn thisThe most common Linux commands(such as cd, mkdir, pwd usw.)
- official venv documentation: If you want to know all the details and options of the command line
Our premium courses offer an excellent user experience with short, easy-to-understand lessons, progress tracking, quizzes to test your knowledge, and practice sessions. You will receive a downloadable course certificate for each course.
FAQs
How do I enable and disable virtual environment in Python? ›
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).
What happens when you deactivate a venv? ›To deactivate:
This exits the entire shell the venv is in, and drops you back to the original shell from before the activation script made any changes to the environment.
To remove/delete virtualenv there is no command for deleting your virtual environment. Simply deactivate it and it will be removed. Note one thing that this process will be the same for every virtual environment regardless of what kind of virtual environment you are using.
How do I turn off virtual environment? ›You can exit from the virtualenv using exit command, or by pressing Ctrl+d.
How do I enable 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.
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.
What happens if you don't deactivate a virtual environment? ›By deactivating, you 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 the venv.
What happens when you activate a virtual environment? ›Activating a virtual environment will put the virtual environment-specific python and pip executables into your shell's PATH . As long as your virtual environment is activated pip will install packages into that specific environment and you'll be able to import and use packages in your Python application.
How do I enable virtual environment in Python automatically? ›Simply cd into a project directory with a python virtual environment setup (with any of these names: venv/ , . venv/ , env or . env ), and the script will activate it automatically for you (just as you would do with source ./venv/bin/activate ).
How do I activate venv scripts? ›To activate virtualenv on Windows, first, install the pip. For this purpose, you can download and execute the latest Python installer. Next, install and create virtualenv on Windows using the pip package manager. Then, activate it using the “venvironment\Scripts\activate” command.
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 reset VENV in Python? ›- 1) Use a requirements. txt file to record what packages you're using. ...
- 2) Remove your old virtualenv. Using plain virtualenvs: rm -rf /home/myusername/path/to/virtualenv. ...
- 3) Create a new virtualenv. ...
- 4) Reinstall your packages. ...
- 5) Restart your web app. ...
- 6) All done!
- Take a Backup of Installed Libraries. You can also take the backup of the installed libraries. ...
- Uninstall all Packages from Virtualenv using Pip Tool. You might have requirement file in your project. ...
- Remove All Python Libraries All At Once.
...
To use pipenv to uninstall a package locally in a virtual environment created with venv or virtualenv:
- Open a command or terminal window (depending on the operating system)
- cd into the project directory.
- pipenv uninstall <packagename>
To leave a Python virtual environment, you can use the deactivate command. This will return you to the system's default Python environment. You can also use the exit command to leave the virtual environment, but this will terminate the terminal session.
Can I reuse a virtual environment? ›Once you have create a new virtual environment, you can reuse it for your other projects. Learn more how to setup an existing environment as a Python interpreter.
What is a venv 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 set environment variables in venv? ›If you want to set environment variables each time the venv is started, you can assign them inside the activation script. If you're running a PowerShell terminal, you should edit Activate. ps1 in <YOUR_ENV>/Scripts and add an extra line to set an environment variable as follows.
How do I set environment variables manually? ›- On the Windows taskbar, right-click the Windows icon and select System.
- In the Settings window, under Related Settings, click Advanced system settings. ...
- On the Advanced tab, click Environment Variables. ...
- Click New to create a new environment variable.
- With the environ dictionary variable value of the environment variable can be set by passing the key in the dictionary and assigning the value to it.
- With setdefault a default value can be assigned to the environment variable. Bypassing the key and the default value in the setdefault method.
Should I use virtualenv or venv? ›
Traditionally virtualenv has been the library used to create virtual environments for python. However , starting python 3.3 , module venv has been added to python standard library and can be used as a drop-in replacement for virtualenv. If older version of python is being used, then virtualenv is the way to go.
Is venv better than 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.
Should I make a new venv for each project? ›You should always create a virtual environment. It's easy to interact with, and it allows you to avoid conflicts between projects.
What is the benefit of creating a virtual environment? ›Virtual environments let you have a stable, reproducible, and portable environment. You are in control of which packages versions are installed and when they are upgraded. You can have as many venvs as you want.
Do virtual environments take up space? ›Well, you are right, virtual environments are somehow a waste of disk space because they are meant to create isolated environments that have -almost- no dependencies outside themselves.
How much space does a virtual environment take? ›The total space consumed by virtualenvs is over 6GB. Also, there are a lot of packages which are common across all the environments and there are few packages which are different. Is there a better way to organize the dependencies so that disk space can be reduced?
What are some of the risks to using a virtualized environment? ›- Data Breaches.
- Weak Identity, Credential, and Access Management.
- Insecure APIs.
- System and Application Vulnerabilities.
- Account Hijacking.
- Malicious Insiders.
- Advanced Persistent Threats (APTs)
- Data Loss.
PROS: You can use any version of python you want for a specific environment without having to worry about collisions (shoutout to my python 2.7 mac users!) You can organize your packages much better and know exactly the packages you need to run your code incase someone else needs to run it on their machine.
Can I delete a virtual environment? ›There is no command for deleting your virtual environment. Simply deactivate it and rid your application of its artifacts by recursively removing it. Note that this is the same regardless of what kind of virtual environment you are using.
How do I create a virtual environment in Python offline? ›- Install Python Packages (Offline)
- Create Virtual Environment.
- Edit Default Setting of Jupyter Notebook.
- Install Jupyter Notebook Extension (Offline)
- Set Up GPU for Tensorflow.
Does Pycharm automatically activate VENV? ›
Pycharm does not activate virtualenv automatically in powershell.
How do I activate venv terminal? ›...
Just do:
- enter in your terminal venv directory( cd venv/Scripts/ )
- You will see activate. bat.
- Just enter activate. bat in your terminal after this you will see YOUR ( venv )
You generally don't need to know the path to the virtual environment Pipenv creates. To activate the environment, just navigate to your project directory and use pipenv shell to launch a new shell session or use pipenv run <command> to run a command directly.
How to activate Python environment in cmd? ›Open the Windows Command Prompt enter into your Desktop folder with the command cd desktop . You can find your device's command line interface (CLI) by searching in your applications.> Type py -m venv env to create a virtual environment named env . When the environment is created, the prompt will reappear.
Should venv be hidden? ›venv suggests it's private. So would not recommend that at all.
Where should my venv be? ›The virtual environment tool creates a folder inside the project directory. By default, the folder is called venv , but you can give it a custom name too. It keeps Python and pip executable files inside the virtual environment folder.
How do you completely reset Python? ›You can try sudo apt purge python-pip python-dev , or python3 and python3-pip if you're using Python 3. This must remove all files/folders created by the installed packages.
How do I clean my 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 update my VENV Python? ›- Backup venv requirements (optional) First of all, backup the requirements of the virtual environment: pip freeze > requirements.txt deactivate #Move the folder to a new one mv venv venv_old.
- Install Python. ...
- Create the new virtual environment.
- Method -1- Using apt parameters. autoremove. clean. autoclean.
- Method -2- Using the popcon-largest-unused command.
- Method -3- Using the deborphan command.
- Method -4- Using unusedpkg (Bash Script)
How do I remove all packages from Python environment? ›
You can use pip uninstall -y -r <(pip freeze) to do everything in one go.
How do I remove specific packages? ›Removing a local package from your node_modules directory
To remove a package from your node_modules directory, on the command line, use the uninstall command. Include the scope if the package is scoped.
- To remove a package such as SciPy in an environment such as myenv: conda remove -n myenv scipy.
- To remove a package such as SciPy in the current environment: conda remove scipy.
- To remove multiple packages at once, such as SciPy and cURL: ...
- To confirm that a package has been removed:
Open the command prompt. With the help of "PIP uninstall module_name” command, uninstall the module. The flask package will be deleted. In the Python 2.7 version, flask uninstall through pip.
How do I reactivate my virtual environment? ›- Activate your virtualenv, using source /home/myusername/path/to/virtualenv/bin/activate or, if you're using virtualenvwrapper workon my-virtualenv-name.
- Save the list of packages to a requirements file. ...
- Double-check which version of python is in your virtualenv. ...
- Deactivate the virtualenv.
- Install Python.
- Install Pip.
- Install VirtualEnv.
- Install VirtualEnvWrapper-win.
To activate virtualenv on Windows, first, install the pip. For this purpose, you can download and execute the latest Python installer. Next, install and create virtualenv on Windows using the pip package manager. Then, activate it using the “venvironment\Scripts\activate” command.
How do I enable Python virtual environment in 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.
Do I have to activate virtual environment 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 know if my venv is active? ›Note: Before installing a package, look for the name of your virtual environment within parentheses just before your command prompt. In the example above, the name of the environment is venv . If the name shows up, then you know that your virtual environment is active, and you can install your external dependencies.
Should I use venv or virtualenv? ›
Traditionally virtualenv has been the library used to create virtual environments for python. However , starting python 3.3 , module venv has been added to python standard library and can be used as a drop-in replacement for virtualenv. If older version of python is being used, then virtualenv is the way to go.
How do I run a Python code in a virtual environment? ›- Create and activate virtual environment using Python 3: python3 -m venv venv source venv/bin/activate.
- Suppose the required packages are listed in requirements.txt : numpy==1.22. ...
- Install the required packages: pip install -r requirements.txt.
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 to activate virtual environment in Python cmd? ›Open the Windows Command Prompt enter into your Desktop folder with the command cd desktop . You can find your device's command line interface (CLI) by searching in your applications.> Type py -m venv env to create a virtual environment named env . When the environment is created, the prompt will reappear.
Where should I put my Python virtual environment? ›The virtual environment tool creates a folder inside the project directory. By default, the folder is called venv , but you can give it a custom name too. It keeps Python and pip executable files inside the virtual environment folder.
Do I have to use virtual environment in Python? ›A virtual Environment should be used whenever you work on any Python-based project. It is generally good to have one new virtual environment for every Python-based project you work on. So the dependencies of every project are isolated from the system and each other.