Установка и использование virtualenv в Python
virtualenv — это инструмент для создания изолированной среды Python. У такой среды есть отдельна установка python, при ее использовании загруженные библиотеки недоступны другим. Можно сделать так, чтобы у этой среды не было доступа к глобальным библиотекам.
Virtualenv — простой и рекомендованный способ настройки среды Python.
Отличия virtualenv и venv
Venv — это пакет, который идет по умолчанию с Python 3.3+. В версии Python 2 его нет.
Virtualenv — более продвинутая библиотека. По ссылке можно ознакомиться с основными отличиями.
Виртуальную среду можно создать и с помощью venv, но все-таки рекомендуется установить и использовать virtualenv для полноценной работы.
Установка virtualenv с помощью pip
Для установки virtualenv с Python нужно использовать pip. Желательно предварительно обновить этот инструмент.
python -m pip install --upgrade pip
Или используйте python3 , если python ссылается на 2 версию.
После обновления можно установить и virtualenv:
pip install virtualenv # или pip3
Создание виртуальной среды
1. Перейдите в директорию, в которой вы хотите создать виртуальную среду(например папка проекта).
~$ cd test ~/test$
2. Создайте виртуальную среду, при необходимости указав конкретную версию Python. Следующая команда создает virtualenv с именем venv_name и использует флаг -p , чтобы указать полный путь к версии Python:
virtualenv -p /usr/bin/python venv_name # или virtualenv venv_name
Назвать среду можно как угодно
После выполнения команды вы увидите логи:
Running virtualenv with interpreter /usr/bin/python Already using interpreter /usr/bin/python Using base prefix '/usr' New python executable in /home/username/test/venv_name/bin/python Installing setuptools, pip, wheel. done.
Эта команда создает локальную копию среды. Работая с ней, важно не забывать об активации, чтобы использовались нужные версии конкретных инструментов и пакетов.
Если при установке возникла ошибка setuptools pip failed with error code 1` error , используйте следующую команду, чтобы решить проблему:
pip install --upgrade setuptools # или pip3
3. Для активации новой виртуальной среды используйте команду:
source venv_name/bin/activate
После этого название текущей среды отобразится слева от символа ввода: (venv_name) username@desctop:~/test$
Теперь при установке любого пакета с помощью pip он будет размещаться в папках этой среды, изолированно от глобальной установки.
Деактивации virtualenv
После завершения работы деактивировать виртуальную среду можно с помощью команды deactivate .
Введите ее и приставка venv_name пропадет. Вы вернетесь к использованию глобально версии python.
Удаление виртуальной среды
Для удаления виртуальной среды достаточно просто удалить папку проекта. Для этого используется следующая команда:
rm -rf venv_name
Решение популярных ошибок
Ошибки при создании virtualenv. При попытке создать virtualenv с Python 3.7 могут возникнуть следующие ошибки.
AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' OSError: Command /home/username/venv/bin/python3 -c "import sys, pip; sys. d\"] + sys.argv[1:]))" setuptools pip failed with error code 1
Для их исправления нужно добавить следующую строку в .bash_profile.
export LC_ALL="en_US.UTF-8"
Использование полного пути к виртуальной среде. Может быть такое, что при использовании команды virtualenv будет использована не та версия. Для решения проблемы нужно лишь задать полные пути как к virtualenv, так и к Python в системе.
А получить их можно с помощью этой команды:
/home/username/opt/python-3.8.0/bin/virtualenv -p /home/username/opt/python-3.8.0/bin/python3 venv
Вопрос №36466 от пользователя M P в уроке «Виртуальные окружения», курс «Python: Настройка окружения»
Добрый день. А как удалить виртуальное окружение? Достаточно удалить соответствующую директорию (.venv)?
Да, достаточно удалить директорию.
Aleksei Pirogov, Понял, спасибо.
Используйте Хекслет по-максимуму!
- Задавайте вопросы по уроку
- Проверяйте знания в квизах
- Проходите практику прямо в браузере
- Отслеживайте свой прогресс
Рекомендуемые программы
• от 6 300 ₽ в месяц
Разработка фронтенд-компонентов для веб-приложений
10 месяцев •
Старт 2 ноября
• от 5 025 ₽ в месяц
Сбор, анализ и интерпретация данных
Старт 2 ноября
• от 6 300 ₽ в месяц
Разработка веб-приложений на Django
10 месяцев •
Старт 2 ноября
• от 6 300 ₽ в месяц
Разработка приложений на языке Java
10 месяцев •
Старт 2 ноября
• от 6 300 ₽ в месяц
Разработка веб-приложений на Laravel
10 месяцев •
Старт 2 ноября
• от 6 183 ₽ в месяц
Ручное тестирование веб-приложений
Старт 2 ноября
• от 6 300 ₽ в месяц
Разработка бэкенд-компонентов для веб-приложений
10 месяцев •
Старт 2 ноября
• от 10 080 ₽ в месяц
Разработка фронтенд- и бэкенд-компонентов для веб-приложений
16 месяцев •
Старт 2 ноября
• от 5 840 ₽ в месяц
Создание веб-приложений со скоростью света
Старт 2 ноября
Верстка с использованием последних стандартов CSS
Старт в любое время
Автоматизированное тестирование веб-приложений на JavaScript
в разработке
дата определяется
- 8 800 100 22 47 бесплатно по РФ
- +7 495 085 28 38 бесплатно по Москве
Направления
- Курсы «Backend-разработка»
- Курсы «Frontend-разработка»
- Курсы «Создание сайтов»
- Курсы «Тестирование»
- Курсы «Аналитика данных»
- Интенсивные курсы
- Курсы DevOps
- Курсы «Веб-разработка»
- Курсы «Математика для программистов»
- Все курсы
О Хекслете
- О нас
- Карьера в Хекслете
- Хекслет Колледж
- Сведения об образовательной организации
- Лицензия № Л035-01216-73/00668844
ООО «Хекслет Рус» 432071, г. Ульяновск, пр-т Нариманова, дом 1Г, оф. 23 ОГРН 1217300010476
- Справка
- Вопросы и ответы
- Сообщество
- Дополнительно
- Условия использования
- Соглашение об обработке ПД
- Оферта
- Акции
Python venv: How To Create, Activate, Deactivate, And Delete

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
Table of Contents
- 1 Why you need virtual environments
- 2 Virtual environments vs. other options
- 3 How to create a Python venv
- 4 Python venv activation
- 5 How a Python venv works
- 6 Deactivate the Python venv
- 7 Deleting a Python venv
- 8 Follow the course
- 9 Learn more
- 10 Conclusion
Why you need virtual environments
There are multiple reasons why virtual environments are a good idea, and this is also 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 installing third-party packages system-wide is very efficient. 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 of library X . In the future, you might need to upgrade library X. Say, for example, you need the latest version for another project you started, called Project B. You upgrade library X to the latest version, and project B works fine. Great! But once you did this, it turns out your Project A code 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.
Sale Product on sale

Modules, Packages, And Virtual Environments (2023)
5.00 out of 5
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 administrator (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:
- In the most extreme case, you could buy a second PC and run your code there. Problem fixed! It was a bit expensive, though!
- 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.
- Next in line is containerization, 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 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, using this article. I just want to ensure that you know 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
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. So the command, in that case, would become:
python -m venv venv
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.exe venv\Scripts\activate.bat # In PowerShell venv\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.
How a Python venv works
When you activate a virtual environment, your PATH variable is changed. On Linux and MacOS, you can see it for yourself by printing the path with echo $PATH . On Windows, use echo %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 looks 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 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:

You can see that:
- The Python command is made available as both python and python3 (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 pip and pip3, and even more specifically under the name pip3.7 because 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 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.
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 this:
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.7 test-O3eWbxRl-py3.6 test-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
Follow the course
Stop feeling like a voodoo coder and learn this stuff properly once and for all. Our Python Fundamentals course extensively explains Modules and packages, Virtual environments, and Package managers. Give it a try, I assure you that you’ll like it!
Learn more
This article is part of a free Python Tutorial. You can browse the tutorial with the navigation buttons at the top and bottom of the article or use the navigation menu. Want to learn more? Here are some great follow-up reads:
- 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
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 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.
Get certified with our courses
Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.
How do I remove/delete a virtualenv?
I created an environment with the following command: virtualenv venv —distribute Trying to remove it with the following command: rmvirtualenv venv does not work. I do an ls on my current directory and I still see venv The only way I can remove it seems to be: sudo rm -rf venv Note that the environment is not active. I’m running Ubuntu 11.10. Any ideas? I’ve tried rebooting my system to no avail.
20.8k 67 67 gold badges 76 76 silver badges 102 102 bronze badges
asked Jun 12, 2012 at 21:54
wulymammoth wulymammoth
8,211 4 4 gold badges 19 19 silver badges 19 19 bronze badges
Just remove the directory.
Jun 12, 2012 at 21:57
honk: sudo rmvirtualenv venv is not a valid command. Not sure why I thought a reboot would help. I’m fairly new, to be a honest.
Jun 12, 2012 at 21:57
Note that rmvirtualenv comes with virtualenvwrapper. You need that installed to make it work.
Apr 7, 2013 at 4:34
Note that you can also remove all currently installed packages, but keep the virtual environment itself if you have virtualenvwrapper installed: $ virtualenv —clear path_to_my_venv . I use this from time to time to make sure I don’t have anything manually installed, like an old dependency no longer in requirements.txt .
Apr 15, 2015 at 16:08
The sudo should not be necessary under normal circumstances. The whole point of a virtual environment is that you can manipulate it using your regular user account.
Apr 13, 2019 at 14:46
22 Answers 22
«The only way I can remove it seems to be: sudo rm -rf venv «
That’s it! 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. virtualenv , venv , Anaconda environment, pyenv , pipenv are all based the same principle here.
4,776 3 3 gold badges 17 17 silver badges 26 26 bronze badges
answered Jun 12, 2012 at 21:58
Thomas Anthony Thomas Anthony
7,963 1 1 gold badge 14 14 silver badges 7 7 bronze badges
It’s worth noting that if you are using pip to install dependencies, you might want to pip freeze a dependency list and keep at the top level directory. If you later choose to deploy your application, you won’t have a bit of trouble.
Jun 12, 2012 at 22:18
Why is this accepted and with this much votes, when the correct answer is just bellow? Maybe this was for an older version of virtualenvwarpper
Aug 28, 2015 at 15:11
@jsbueno He was using virtualenv, not virtualenvwrapper (they are not the same program). At the time, virtualenv provided no interface for clean up; you had to do it yourself.
Jan 23, 2016 at 2:12
If you’ve created a virtualenv in a git repo (and the files are not ignored): git clean -dffx
Feb 22, 2018 at 3:35
From a suggested edit: «I think this is not strictly speaking valid for conda environments, as Anaconda makes other changes on file system which won’t be covered by ‘rm -rf. ‘, e.g. user-specific environments.txt file may also need to be edited?»
Mar 10, 2022 at 21:33
Just to echo what @skytreader had previously commented, rmvirtualenv is a command provided by virtualenvwrapper , not virtualenv . Maybe you didn’t have virtualenvwrapper installed?
answered Sep 4, 2013 at 22:23
9,753 8 8 gold badges 61 61 silver badges 59 59 bronze badges
rmvirtualenv is a command for virtualenvwrapper. It won’t work if you don’t have that installed.
Using virtualenvwrapper, to remove an environment, in the $WORKON_HOME :
rmvirtualenv ENVNAME
You must use deactivate before removing the current environment.
$ rmvirtualenv my_env
20.8k 67 67 gold badges 76 76 silver badges 102 102 bronze badges
answered Oct 24, 2016 at 5:16
Antoniazzi Antoniazzi
1,662 1 1 gold badge 10 10 silver badges 10 10 bronze badges
there is even tab completion support for this!
Feb 8, 2017 at 19:47
You can remove all the dependencies by recursively uninstalling all of them and then delete the venv.
source venv/bin/activate pip freeze > requirements.txt pip uninstall -r requirements.txt -y deactivate rm -r venv/
20.8k 67 67 gold badges 76 76 silver badges 102 102 bronze badges
answered May 11, 2016 at 6:11
Dawn T Cherian Dawn T Cherian
4,998 3 3 gold badges 24 24 silver badges 35 35 bronze badges
And critically only do this if you are not sharing the system’s pip ! (Otherwise you will uninstall all of your system packages.)
Jan 9, 2018 at 17:29
Actually there should be no need to separately pip uninstall if you are removing all the packages by way of rm anyway. Skipping that stepealso avoids the risk pointed out in the previous comment.
Apr 13, 2019 at 14:43
rm -r venv/ did it for me, no need for the other steps indeed
Nov 11, 2022 at 8:15
If you are using pyenv, it is possible to delete your virtual environment:
$ pyenv virtualenv-delete
answered May 7, 2019 at 10:06
Christiaan Herrewijn Christiaan Herrewijn
1,051 10 10 silver badges 11 11 bronze badges
You can also run pyenv uninstall
Oct 22, 2021 at 10:10
@giorgio in my case pyenv uninstall
Oct 14, 2022 at 11:04
I need to correct myself: On some systems pyenv uninstall
Oct 14, 2022 at 11:24
Simply delete the virtual environment from the system:
rm -rf venv
(There’s no special command for it)
2,235 3 3 gold badges 19 19 silver badges 15 15 bronze badges
answered Sep 21, 2016 at 18:16
Naveen Agarwal Naveen Agarwal
958 7 7 silver badges 7 7 bronze badges
Works on me. Make sure to deactivate first if your virtual environment is still running. (your virtual env)>deactivate >rm -rf «your virtual env»
Dec 2, 2019 at 2:22
I find that the -f flag is not needed. I prefer to avoid that flag when possible.
Jun 11, 2020 at 17:02
Removing an Environment
Removing a virtual environment is simply done by deactivating it and deleting the environment folder with all its contents:
(ENV)$ deactivate $ rm -r /path/to/ENV
2,235 3 3 gold badges 19 19 silver badges 15 15 bronze badges
answered Mar 3, 2018 at 12:27
996 7 7 silver badges 14 14 bronze badges
@Sébastien No, you should not need sudo or similar privileges unless you also used them to set up the environment in the first place, which would usually be an error.
Apr 13, 2019 at 14:40
1. Remove the Python environment
There is no command to remove a virtualenv so you need to do that by hand, you will need to deactivate if you have it on and remove the folder:
deactivate rm -rf
2. Create an env. with another Python version
When you create an environment the python uses the current version by default, so if you want another one you will need to specify at the moment you are creating it. To make and env. with Python 3.X called MyEnv just type:
python3.X -m venv MyEnv
Now to make with Python 2.X use virtualenv instead of venv :
python2.X -m virtualenv MyEnv
3. List all Python versions on my machine
If any of the previous lines of code didn’t worked you probably don’t have the specific version installed. First list all your versions with:
ls -ls /usr/bin/python*
If you didn’t find it, install Python 3.X using apt-get :
sudo apt-get install python3.X