Как выйти из виртуального окружения python
Перейти к содержимому

Как выйти из виртуального окружения python

  • автор:

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

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.

Python Fundamentals II: Modules, Packages, Virtual Environments

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:

  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 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:

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:

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:

Once installed, you can create a virtual environment with:

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:

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:

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:

And on Linux and MacOS:

A Python venv directory tree

Virtualenv directory tree

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:

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:

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:

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:

You’ll get a list like this:

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:

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 is a better way of managing your venv and packages.
  • Learn the most common Linux commands (like cd, mkdir, pwd, etcetera) : If you want to know all the details and command-line options


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

Our premium courses offer a superior user experience with small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Course for Beginners

Python Fundamentals II: Modules, Packages, Virtual Environments

NumPy Course: The Hands-on Introduction To NumPy

Learn more

This article is part of the free Python tutorial. You can head over to the start of the tutorial here. You can navigate this tutorial using the buttons at the top and bottom of the articles. To get an overview of all articles in the tutorial, please use the fold-out menu at the top.

If you liked this article, you might also like to read the following articles:

Как выйти из виртуального окружения python

A Virtual Environment in Python helps you to manage different versions of Python for different projects without doing a mess with your default system dependencies. It allows you to manage separate environments for different packages for different projects. This is one of the most important tools that most Python developers use.

Why would you use a virtual environment Python?

Let’s say you’re working on a project which uses Python3.10 and your default system interpreter is Python3.8 and uses the 1.0 version of that dependency then you need to have Python3.10 installed in order to work on that project.
To get rid of these painful experiences, virtualenv helps you to isolate your different Python environments, dependencies, etc and you can create as many virtual environments as you want. While developing Python applications it is recommended to use a virtual environment to preserve conflicts.

Creating a Virtual Environment

Step 1: Install the virtualenv package.

Install a Virtual Environment Python

Now check your installation

Step 2: Create a virtual environment. After running the below command, a directory named virtualenv_name will be created. This is the directory that contains all the necessary executables to use the packages that a Python project would need.

Step 3: Create a new virtual environment

where venv is the name of the virtual environment you can change it accordingly

Creating a Virtual Environment Python

Step 4: Activate our newly created virtual environment

Activate a Virtual Environment Python

If everything works well then the name of your virtual environment will appear on the left side of the terminal as shown in the above image which means that the virtual environment is currently active.

Deactivate the Virtual Environment

After you finish working deactivate your virtual environment by simply executing the below command.

Deactivate a Virtual Environment Python

As you can see in the above image the name of our virtual environment disappeared.

Управление средами Python на профессиональном уровне


Виртуальные среды Python помогают легко и непринужденно управлять зависимостями. Наиболее распространенными инструментами создания сред являются virtualenv и conda. Последний используется для управления средами на нескольких языках, в то время как первый создан специально для python.

Почему бы не использовать глобальные пакеты python? С ними не придется влезать в эту неразбериху со средами, не так ли? Так-то оно так, глобальные пакеты python экономят наше время, управляя средами, но какой ценой! Проблемы — начиная от подготовки установки до перехода к проекту — будут расти в геометрической прогрессии. Я усвоил это на собственном горьком опыте, используя глобальные пакеты для всего и не имея специальной среды для каждого проекта.

В этой статье я расскажу о virtualenvwrapper (VEW)— библиотеке python для управления и настройки сред на python. Она действует наравне со старым добрым virtualenv. Вы увидите, как команды VEW CLI похожи на команды Linux, такие как mkdir , rmdir и cp .

Примечание: на протяжении всей статьи буду для краткости использовать вместо “virtualenvwrapper” аббревиатуру “VEW”.


Важно отметить, что утилита pyenv не связана с virtualenv или VEW. pyenv используется для переключения между несколькими версиями python и не управляет установленными пакетами. Кроме того, pip — менеджер пакетов на python — тоже не может помочь нам в управлении средой, потому что он не был создан для этого. Для получения дополнительной информации прочтите на stackoverflow, в чем разница между pyenv, virtualenv и anaconda.


Процесс установки такой же, как и в любой другой библиотеке.

В системе Linux после установки необходимо отредактировать файл .bashrc. Это позволит получить доступ к VEW в любом терминале и в любом месте.

  1. Задаем переменную VIRTUALENVWRAPPER_PYTHON , которая указывает на двоичную установку python, на которую следует ссылаться VEW.
  2. WORKON_HOME — это папка, в которой VEW будет хранить все среды и сценарии утилит.
  3. VIRTUALENVWRAPPER_VIRTUALENV — это путь к исходному двоичному файлу virtualenv.

Создание новой виртуальной среды

Как я уже говорил ранее, команды VEW аналогичны командам Linux. Чтобы создать новую среду, выполните следующую строку:

Эта среда будет сохранена по пути, указанному в переменной WORKON_HOME . Наряду с опциями virtualenv, поддерживаются еще три:

  1. -a my_path: папка для среды, куда пользователь, на каком бы пути он ни находился в данный момент, перенаправляется всякий раз, когда среда активируется. Среда не создается внутри my_path.
  2. -i package1 package2: установите указанные пакеты после создания среды.
  3. -r requirements.txt: создайте среду и установите из файла requirements.txt.

Удаление виртуальной среды

Удалите среду из папки. Не забудьте деактивировать ее перед удалением.

Показ подробной информации о среде

Список всех виртуальных сред

Выведите список всех виртуальных сред, созданных с помощью этого инструмента. Используйте опцию -b, чтобы получить только список сред и проигнорировать подробности.

Активация среды

virtualenv использует следующую команду для активации среды:

source — это команда Linux, широко используемая в основном для изменения переменных среды с помощью текущей оболочки. VEW абстрагирует эту исходную команду и предоставляет легкую для запоминания альтернативу под названием workon .

Де-факто VEW выполняет команду source .

Деактивация среды

Деактивация среды в VEW осуществляется так же, как и в virtualenv. В активной оболочке среды выполните следующее:

Удаление пакетов сторонних производителей в среде

Эта команда должна выполняться в активной среде. Когда она будет выполнена, VEW идентифицирует все сторонние библиотеки и удалит их.


Хотя virtualenv отлично работает для управления всеми средами, virtualenvwrapper является рекомендуемым дополнением. Сходство его команд с командами Linux облегчает запоминание операций.

How to leave/exit/deactivate a Python virtualenv

I’m using virtualenv and the virtualenvwrapper. I can switch between virtualenv’s just fine using the workon command.

How do I exit all virtual environments and work on my system environment again? Right now, the only way I have of getting back to me@mymachine:

$ is to exit the shell and start a new one. That’s kind of annoying. Is there a command to work on "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?

Timur Shtatland's user avatar

15 Answers 15

Usually, activating a virtualenv gives you a shell function named:

which puts things back to normal.

I have just looked specifically again at the code for virtualenvwrapper , and, yes, it too supports deactivate as the way to escape from all virtualenvs.

If you are trying to leave an Anaconda environment, the command depends upon your version of conda . Recent versions (like 4.6) install a conda function directly in your shell, in which case you run:

Older conda versions instead implement deactivation using a stand-alone script:

If this doesn’t work, try

Anyone who knows how Bash source works will think that’s odd, but some wrappers/workflows around virtualenv implement it as a complement/counterpart to source activate . Your mileage may vary.

Peter Mortensen's user avatar

I defined an alias, workoff, as the opposite of workon:

It is easy to remember:

Peter Mortensen's user avatar

Bob Stein's user avatar

To activate a Python virtual environment:

Peter Mortensen's user avatar

Amitesh Ranjan's user avatar

Running deactivate [name of your environment] is able to exit/deactivate from your python environment.

Example with python3.6 Windows 10 in PowerShell:

Example with python3.9 on Linux Ubuntu 20.04 LTS Desktop:

I found that when within a Miniconda3 environment I had to run:

Neither deactivate nor source deactivate worked for me.

CephBirk's user avatar

You can use virtualenvwrapper in order to ease the way you work with virtualenv .

If you are using a standard shell, open your

/.zshrc if you use Oh My Zsh. Add these two lines:

To activate an existing virtualenv, use command workon :

In order to deactivate your virtualenv:

Here is my tutorial, step by step on how to install virtualenv and virtualenvwrapper.

Peter Mortensen's user avatar

levi's user avatar

For my particular case, I go to to the working directory

Then I activate my env like this:

From this same working folder ( /myworkingdirectory ) to deactivate, I tried this but it does nothing:

Using the deactivate feature provided by the venv’s activate script requires you to trust the deactivation function to be properly coded to cleanly reset all environment variables back to how they were before— taking into account not only the original activation, but also any switches, configuration, or other work you may have done in the meantime.

It’s probably fine, but it does introduce a new, non-zero risk of leaving your environment modified afterwards.

However, it’s not technically possible for a process to directly alter the environment variables of its parent, so we can use a separate sub-shell to be absolutely sure our venv s don’t leave any residual changes behind:

To activate:

$ bash —init-file PythonVenv/bin/activate

  • This starts a new shell around the venv . Your original bash shell remains unmodified.

To deactivate:

$ exit OR [CTRL] + [D]

  • 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.


Will Chen's user avatar

Since the deactivate function created by sourcing

/bin/activate cannot be discovered by the usual means of looking for such a command in

/bin , you may wish to create one that just executes the function deactivate .

The problem is that a script named deactivate containing a single command deactivate will cause an endless loop if accidentally executed while not in the venv. A common mistake.

This can be avoided by only executing deactivate if the function exists (i.e. has been created by sourcing activate ).

$ conda deactivate
$ source deactivate
would work.

If it doesn’t work, try deactivate [name of your environment] instead.

Léo's user avatar

I my case, I was able to activate virtual environment using env-name\scripts\activate and deactivate it using deactivate . However, after running update on my windows PC deactivate was no longer recognized as an internal or external command. What I used from that moment onward is env-name\scripts\deactivate and that solved the problem.

C-Bizz's user avatar

I use zsh-autoenv which is based off autoenv.

zsh-autoenv automatically sources (known/whitelisted) .autoenv.zsh files, typically used in project root directories. It handles «enter» and leave» events, nesting, and stashing of variables (overwriting and restoring).

Here is an example:

So when I leave the dtree directory, the virtual environment is automatically exited.

«Development tree utiles» is just a name… No hidden mean linking to the Illuminati in here.

Sardathrion - against SE abuse's user avatar

I had the same problem while working on an installer script. I took a look at what the bin/activate_this.py did and reversed it.

I am not 100% sure if it works as intended. I may have missed something completely.

Peter Mortensen's user avatar

If you don’t know how to exit some python environment I would just run

as there is a risk you missed deleting that code for entering to some python environment, which something such as conda/mamba already installed into your .bashrc The conda/mamba enters environments the same way you can run bash inside bash. Default installation forces base environment to be activated by default, which drives me crazy as it might break lot of things, to exit it you just type

But you can configure conda in a way that you activate it only when you use it. Then if you e.g. type

You will actually be in nested environment (xy) and (xy) -deactivate-> (base) -deactivate-> (base) -deactivate-> (env) -deactivate-> no conda/mamba .

So if you are in some environment, do not know how much nested it is and you want to get base environment, you can also use

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *