How to activate virtual environment python windows

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.

  • Product on sale

    Modules, Packages, And Virtual Environments (2023)

    Modules, Packages, And Virtual Environments (2023)

    £ 39.00

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.

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

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:

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.

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 to activate venv virtual environment in Python 3? The venv module is used to create a lightweight virtual environment, this environment is created on top of the existing python installation hence it uses the same version as the current one.

In this article, I will explain how to activate the virtual environment on Windows, Linux, Unix, and Mac OS. Depending on your OS and the shell you are using the activating virtual environment takes different syntaxes.

OS Shell Command
Unix, Linux, or MacOS bash shell source /path/to/venv/bin/activate
Unix, Linux, or MacOS csh shell source /path/to/venv/bin/activate.csh
Unix, Linux, or MacOS fish shell source /path/to/venv/bin/activate.fish
Windows Command Prompt \path\to\venv\Scripts\activate.bat
Windows PowerShell \path\to\venv\Scripts\Activate.ps1
Activating Virtual Environment in Python

1. Create a Virtual Environment

First, let’s create a virtual environment. The below example creates a virtual environment dev-env under the current directory. Here, I will be using the virtual environment module venv that comes with Python 3.3 version.


# Create virtual environment
python3 -m venv dev-env

If you wanted to create at a custom location, just specify the absolute path along with the environment name.


# Create virtual environment
python3 -m venv /path/to/virtual/environment/dev-env

2. Activate Virtual Environment On Linux/MacOS in Python

Once an environment has been created, you may wish to activate it by sourcing an activate script in its bin directory.


# Activate virtual environment
source dev-env/bin/activate

Here, the Virtual environment dev-env has been activated to use. Any command you run after this will execute in a virtual environment.

3. Active Virtual Environment on Windows

On Windows, when you are using windows prompt you can activate Python virtual environment by running the activate.bat file from the bin directory, and when using PowerShell run the Activate.ps1 from the Scripts directory.


# Activate virtual environment on windows

# From command prompt
dev-env\bin\activate.bat

# From power shell
dev-env\Scripts\Activate.ps1

4. Check the Current Active Virtual Environment

Sometimes while working in the virtual environment, we may be required to get the environment you are in. There is no direct command to get this information, however, you can get it from the environment variable $VIRTUAL_ENV.


# Current virtual environment
# On Linux or MacOS
echo $VIRTUAL_ENV

# On windows
%VIRTUAL_ENV%

Conclusion

In this article, you have learned how to activate a virtual environment in Windows, Linux, Unix, and mac OS. These methods are used only if you use the venv module. Note that depending on the OS and shell you are using the command to activate changes so keep an eye on what you are running.

Содержание:развернуть

  • Настройка виртуального окружения
  • Создание

  • Активация

  • Автоматическая активация

  • Деактивация

  • Альтернативы venv

Все сторонние пакеты устанавливаются менеджером PIP глобально. Проверить это можно просто командой pip show <имя_пакета>.

root@purplegate:~# pip3 show pytest
Name: pytest
Version: 5.3.2
Summary: pytest: simple powerful testing with Python
Home-page: https://docs.pytest.org/en/latest/
Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, ...
License: MIT license
Location: /usr/local/lib/python3.8/site-packages
Requires: more-itertools, pluggy, py, wcwidth, attrs, packaging
Required-by:

Location — путь до ваших глобальных пакетов.

В большинстве случаев, устанавливать пакеты глобально — плохая идея 🙅‍♂️ Почему? Рассмотрим простой пример:

Допустим у нас есть два проекта: «Project A» и «Project B». Оба проекта зависят от библиотеки Simplejson. Проблема возникает, когда для «Project A» нужна версия Simplejson 3.0.0, а для проекта «Project B» — 3.17.0. Python не может различить версии в глобальном каталоге site-packages — в нем останется только та версия пакета, которая была установлена последней.

Решение данной проблемы — создание виртуального окружения (virtual environment).

Основная цель виртуального окружения Python — создание изолированной среды для python-проектов

Это означает, что каждый проект может иметь свои собственные зависимости, независимо от других проектов.

Настройка виртуального окружения

Один из самых популярных инструментов для создания виртуального окружения — virtualenv. Однако в данной статье мы будем рассматривать более свежий инструмент venv.

Устанавливать venv не нужно — он входит в стандартную библиотеку Python

Создание

Для создания виртуального окружения, перейдите в директорию своего проекта и выполните:

python -m venv venv

-m — флаг для запуска venv как исполняемого модуля.
venv — название виртуального окружения (где будут храниться ваши библиотеки).

В результате будет создан каталог venv/ содержащий копию интерпретатора Python, стандартную библиотеку и другие вспомогательные файлы. Все новые пакеты будут устанавливаться в venv/lib/python3.x/site-packages/.

Содержимое каталога venv.

Виртуальное окружение также можно создать в IDE PyCharm, для этого:

  1. Зайдите в настройки интерпретатора («Settings» → «Project:<name>» → «Project Interpreter«);
  2. Нажмите на шестеренку в верхнем правом углу, выберите «Add..«;
  3. Выберите «Virual Enviroment» и задайте параметры.

Создание виртуального окружения в IDE PyCharm.

Активация

Чтобы начать пользоваться виртуальным окружением, необходимо его активировать:

  • venv\Scripts\activate.bat — для Windows;
  • source venv/bin/activate — для Linux и MacOS.

source выполняет bash-скрипт без запуска дополнительного bash-процесса.

Проверить успешность активации можно по приглашению оболочки. Она будет выглядеть так:

(venv) root@purplegate:/var/test#

Также новый путь до библиотек можно увидеть выполнив команду:

python -c "import site; print(site.getsitepackages())"

Если вы используете IDE PyCharm, то при открытии проекта он автоматически найдет созданное виртуальное окружение и уведомит о его использовании. Проверить настройки виртуального окружения можно в «Settings» → «Project:<name>» → «Project Interpreter» (путь до интерпретатора должен быть вида [путь до проекта]/venv/Scripts/python.exe).

Интересный факт: в виртуальном окружении вместо команды python3 и pip3, можно использовать python и pip

Автоматическая активация

В некоторых случаях, процесс активации виртуального окружения может показаться неудобным (про него можно банально забыть 🤷‍♀️).

На практике, для автоматической активации перед запуском скрипта, создают скрипт-обертку на bash:

#!/usr/bin/env bash

source $BASEDIR/venv/bin/activate
python $BASEDIR/my_app.py

Теперь можно установить права на исполнение и запустить нашу обертку:

chmod +x myapp/run.sh
./myapp/run.sh

Деактивация

Закончив работу в виртуальной среде, вы можете отключить ее, выполнив консольную команду:

deactivate

Альтернативы venv

На данный момент существует несколько альтернатив для venv:

  • pipenv — это pipfile, pip и virtualenv в одном флаконе;
  • pyenv — простой контроль версий Питона;
  • poetry — новый менеджер для управления зависимостями;
  • autoenv — среды на основе каталогов;
  • pew — инструмент для управления несколькими виртуальными средами, написанными на чистом Python;
  • rez — интегрированная система конфигурирования, сборки и развертывания пакетов для программного обеспечения.

Стоит ли использовать виртуальное окружение в своей работе — однозначно да. Это мощный и удобный инструмент изоляции проектов друг от друга и от системы. С помощью виртуального окружения можно использовать даже разные версии Python!

Однако рекомендуем присмотреться к более продвинутым вариантам, например к pipenv или poetry.

How to connect create a Python Virtual Environment

It is often useful to have one or more Python environments where you can experiment with different combinations of packages without affecting your main installation. Python supports this through virtual environments. The virtual environment is a copy of an existing version of Python with the option to inherit existing packages. A virtual environment is also useful when you need to work on a shared system and do not have permission to install packages as you will be able to install them in the virtual environment.

Outline

  • Open a terminal
  • Setup the pip package manager
  • Install the virtualenv package
  • Create the virtual environment
  • Activate the virtual environment
  • Deactivate the virtual environment
  • Optional: Make the virtual environment your default Python
  • More: Python virtualenv documentation

Requirements

  • An installation of Python

Jargon

Link to Jargon page with terms: terminal

Open a terminal

The method you use to open a terminal depends on your operating system.

Windows

Open the Windows Command Prompt (show path via Start menu and keyboard shortcuts)

Mac OS / Linux

Open the Terminal program. This is usually found under Utilities or Accessories.

Setup the pip package manager

Check to see if your Python installation has pip. Enter the following in your terminal:

If you see the help text for pip then you have pip installed, otherwise download and install pip

Install the virtualenv package

The virtualenv package is required to create virtual environments. You can install it with pip:

Create the virtual environment

To create a virtual environment, you must specify a path. For example to create one in the local directory called ‘mypython’, type the following:

Activate the virtual environment

You can activate the python environment by running the following command:

Mac OS / Linux

source mypython/bin/activate

Windows

You should see the name of your virtual environment in brackets on your terminal line e.g. (mypython).

Any python commands you use will now work with your virtual environment

Deactivate the virtual environment

To decativate the virtual environment and use your original Python environment, simply type ‘deactivate’.

Optional: Make the virtual environment your default Python

More: Python virtualenv documentation

For more detailed information, see the offical virtualenv documentation

How to Set Up a Virtual Environment in Python – And Why It's Useful

When developing software with Python, a basic approach is to install Python on your machine, install all your required libraries via the terminal, write all your code in a single .py file or notebook, and run your Python program in the terminal.

This is a common approach for a lot of beginners and many people transitioning from working with Python for data analytics.

This works fine for simple Python scripting projects. But in complex software development projects, like building a Python library, an API, or software development kit, often you will be working with multiple files, multiple packages, and dependencies. As a result, you will need to isolate your Python development environment for that particular project.

Consider this scenario: you are working on app A, using your system installed Python and you pip install packageX version 1.0 to your global Python library. Then you switch to project B on your local machine, and you install the same packageX but version 2.0, which has some breaking changes between version 1.0 and 2.0.

When you go back to run your app A, you get all sorts of errors, and your app does not run. This is a scenario you can run into when building software with Python. And to get around this, we can use virtual environments.

This tutorial will cover everything you need to know about virtual environments and how to set one up with Virtualenv.

Python’s official documentation says:

«A virtual environment is a Python environment such that the Python interpreter, libraries and scripts installed into it are isolated from those installed in other virtual environments, and (by default) any libraries installed in a “system” Python, i.e., one which is installed as part of your operating system»

To break this down, when you activate a virtual environment for your project, your project becomes its own self contained application, independent of the system installed Python and its modules.

Your new virtual environment has its own pip to install libraries, its own libraries folder, where new libraries are added, and its own Python interpreter for the Python version you used to activate the environment.

With this new environment, your application becomes self-contained and you get some benefits such as:

  • Your development environment is contained within your project, becomes isolated, and does not interfere with your system installed Python or other virtual environments
  • You can create a new virtual environment for multiple Python versions
  • You are able to download packages into your project without admin privileges
  • You can easily package your application and share with other developers to replicate
  • You can easily create a list of dependencies and sub dependencies in a file, for your project, which makes it easy for other developers to replicate and install all the dependencies used within your environment

Using virtual environments is recommended for software development projects that generally grow out of a single Python script, and Python provides multiple ways of creating and using a virtual environment.

In the sections below, we will walk through how to set up your virtual environment, using venv, which gives you a lot more low level control of your environment.

Another common way to set up your virtual environment is to use pipenv, which is a more high level approach.

How to Install a Virtual Environment using Venv

Virtualenv is a tool to set up your Python environments. Since Python 3.3, a subset of it has been integrated into the standard library under the venv module. You can install venv to your host Python by running this command in your terminal:

pip install virtualenv

To use venv in your project, in your terminal, create a new project folder, cd to the project folder in your terminal, and run the following command:

 python<version> -m venv <virtual-environment-name>

Like so:

 mkdir projectA
 cd projectA
 python3.8 -m venv env

When you check the new projectA folder, you will notice that a new folder called env has been created. env is the name of our virtual environment, but it can be named anything you want.

If we check the contents of env for a bit, on a Mac you will see a bin folder. You will also see scripts that are typically used to control your virtual environment, such as activate and pip to install libraries, and the Python interpreter for the Python version you installed, and so on. (This folder will be called Scripts on windows).

The lib folder will contain a list of libraries that you have installed. If you take a look at it, you will see a list of the libraries that come by default with the virtual environment.

How to Activate the Virtual Environment

Now that you have created the virtual environment, you will need to activate it before you can use it in your project. On a mac, to activate your virtual environment, run the code below:

source env/bin/activate

This will activate your virtual environment. Immediately, you will notice that your terminal path includes env, signifying an activated virtual environment.

Note that to activate your virtual environment on Widows, you will need to run the following code below (See this link to fully understand the differences between platforms):

 env/Scripts/activate.bat //In CMD
 env/Scripts/Activate.ps1 //In Powershel

Is the Virtual Environment Working?

We have activated our virtual environment, now how do we confirm that our project is in fact isolated from our host Python? We can do a couple of things.

First we check the list of packages installed in our virtual environment by running the code below in the activated virtual environment. You will notice only two packages – pip and setuptools, which are the base packages that come default with a new virtual environment

pip list

Next you can run the same code above in a new terminal in which you haven’t activated the virtual environment. You will notice a lot more libraries in your host Python that you may have installed in the past. These libraries are not part of your Python virtual environment until you install them.

How to Install Libraries in a Virtual Environment

To install new libraries, you can easily just pip install the libraries. The virtual environment will make use of its own pip, so you don’t need to use pip3.

After installing your required libraries, you can view all installed libraries by using pip list, or you can generate a text file listing all your project dependencies by running the code below:

pip freeze > requirements.txt

You can name this requirements.txt file whatever you want.

Requirements File

Why is a requirements file important to your project? Consider that you package your project in a zip file (without the env folder) and you share with your developer friend.

To recreate your development environment, your friend will just need to follow the above steps to activate a new virtual environment.

Instead of having to install each dependency one by one, they could just run the code below to install all your dependencies within their own copy of the project:

 ~ pip install -r requirements.txt

Note that it is generally not advisable to share your env folder, and it should be easily replicated in any new environment.

Typically your env directory will be included in a .gitignore file (when using version control platforms like GitHub) to ensure that the environment file is not pushed to the project repository.

How to Deactivate a Virtual Environment

To deactivate your virtual environment, simply run the following code in the terminal:

 ~ deactivate

Conclusion

Python virtual environments give you the ability to isolate your Python development projects from your system installed Python and other Python environments. This gives you full control of your project and makes it easily reproducible.

When developing applications that would generally grow out of a simple .py script or a Jupyter notebook, it’s a good idea to use a virtual environment – and now you know how to set up and start using one.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • How to activate venv python windows
  • How can i activate windows
  • Host services for windows services что это за программа
  • How install kali linux with windows 10
  • Host process for windows tasks что это