How to activate virtual environment python windows

How to activate virtual environment python windows

Python Virtual Environments

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

Requirements

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

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

A template for capturing task recipes for repeatable scientific practices in a consistent format and hosted in a centralised online repository

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:

Table of contents

Why you need virtual environments

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

Preventing version conflicts

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

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

Easy to reproduce and install

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

Works everywhere, even when not root

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

Virtual environments vs. other options

There are other options to isolate your project:

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

How to create a Python venv

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

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

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

Python 3.4 and above

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

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

A little further in this article, we’ll look closely at the directory that was just created. 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

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

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?

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:

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windowsVirtualenv directory tree

You can see that:

Deactivate the Python venv

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

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.

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:

Delete a venv with Pipenv

If you used Pipenv, 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:

Conclusion

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

Keep learning

Related posts you might like

About Erik van Baaren

Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He’s been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python! Writing good articles takes time and effort. Did you like this tutorial? You can buy him a coffee to show your appreciation.

How To Set Up A Python Virtual Environment On Windows 10

A Virtual Environment or a «venv» is a Python module that creates a unique environment for each task or project. It installs the packages we need that are unique to that setting while keeping your projects neatly organized. Additionally, venv never actually modifies the system’s default Python versions or modules that are installed on the system. Using venv essentially allows for a unique working environment while avoiding any disruptions to other variants of Python that are used, but not related to our project.

Prerequisites

We recommend enabling the Windows Subsystem for Linux (WSL) in order to take full advantage of all the functionality of venv on Windows 10. This allows you to run a full Linux distribution within Windows to aid in the functionality of the new dev environment.

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Why should I use WSL?

How do I enable WSL?

Install Linux

There are multiple Linux distros that work with WSL. You can locate and install them from the Microsoft Store. We recommend starting off with a Ubuntu 18.04 LTS distribution as it’s up to date, has an excellent support community, and is well documented.

As a side note, Windows does not handle upgrades for this OS so you will need to ensure Ubuntu stays up to date by running the update and upgrade commands manually.

You can then install your distro using PowerShell. To install one of those distros, navigate to the folder which contains the newly downloaded Linux distributions. Once in that folder, run the following command in PowerShell (where app_name.aspx is the name of the distribution file):

Next, we’ll add the path to the distro into your Windows environment PATH using Powershell (eg. C:\Users\Admin\Ubuntu)

Now, we can start the distro by typing in uubuntu.exe. Next, we should initialize the new instance.

Launch a distro

During the last stage of the installation, the distro’s files will be decompressed and stored locally on your PC. This process may take a few minutes but is only required once. Later initializations should take less than a second.

Setup

There are four basic steps to install a virtual environment on windows:

Python Virtual Environments: A Primer

Table of Contents

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Working With Python Virtual Environments

In this tutorial, you’ll learn how to work with Python’s venv module to create and manage separate virtual environments for your Python projects. Each environment can use different versions of package dependencies and Python. After you’ve learned to work with virtual environments, you’ll know how to help other programmers reproduce your development setup, and you’ll make sure that your projects never cause dependency conflicts for one another.

By the end of this tutorial, you’ll know how to:

Virtual environments are a common and effective technique used in Python development. Gaining a better understanding of how they work, why you need them, and what you can do with them will help you master your Python programming workflow.

Free Bonus: Click here to get access to a free 5-day class that shows you how to avoid common dependency management issues with tools like Pip, PyPI, Virtualenv, and requirements files.

Throughout the tutorial, you can select code examples for either Windows, Ubuntu Linux, or macOS. Pick your platform at the top right of the relevant code blocks to get the commands that you need, and feel free to switch between your options if you want to learn how to work with Python virtual environments on other operating systems.

Take the Quiz: Test your knowledge with our interactive “Python Virtual Environments: A Primer” quiz. Upon completion you will receive a score so you can track your learning progress over time:

How Can You Work With a Python Virtual Environment?

If you just need to get a Python virtual environment up and running to continue working on your favorite project, then this section is the right place for you.

The instructions in this tutorial use Python’s venv module to create virtual environments. This module is part of Python’s standard library, and it’s the officially recommended way to create virtual environments since Python 3.5.

Note: There are other great third-party tools for creating virtual environments, such as conda and virtualenv, that you can learn more about later in this tutorial. Any of these tools can help you set up a Python virtual environment.

For basic usage, venv is an excellent choice because it already comes packaged with your Python installation. With that in mind, you’re ready to create your first virtual environment in this tutorial.

Create It

If you’re using Python on Windows and you haven’t configured the PATH and PATHEXT variables, then you might need to provide the full path to your Python executable:

The system path shown above assumes that you installed Python 3.10 using the Windows installer provided by the Python downloads page. The path to the Python executable on your system might be different. Working with PowerShell, you can find the path using the where.exe python command.

Many Linux operating systems ship with a version of Python 3. If python3 doesn’t work, then you’ll have to first install Python, and you may need to use the specific name of the executable version that you installed, for example python3.10 for Python 3.10.x. If that’s the case for you, remember to replace mentions of python3 in the code blocks with your specific version number.

If running python3 doesn’t work, then you’ll have to first install a modern version of Python.

Activate It

Great! Now your project has its own virtual environment. Generally, before you start using it, you’ll first activate the environment by executing a script that comes with the installation:

Before you run this command, make sure that you’re in the folder that contains the virtual environment you just created.

Note: You can also work with your virtual environment without activating it. To do this, you’ll provide the absolute path to its Python interpreter when executing a command. However, most commonly, you’ll want to activate the virtual environment after creating it to save yourself the effort of repeatedly having to type long absolute paths.

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!

Install Packages Into It

After creating and activating your virtual environment, you can now install any external dependencies that you need for your project:

Note: Because you’ve created your virtual environment using a version of Python 3, you don’t need to call python3 or pip3 explicitly. As long as your virtual environment is active, python and pip link to the same executable files that python3 and pip3 do.

Congratulations, you can now install your packages to your virtual environment. To get to this point, you began by creating a Python virtual environment named venv and then activated it in your current shell session.

As long as you don’t close your terminal, every Python package that you’ll install will end up in this isolated environment instead of your global Python site-packages. That means you can now work on your Python project without worrying about dependency conflicts.

Deactivate It

Once you’re done working with this virtual environment, you can deactivate it:

After executing the deactivate command, your command prompt returns to normal. This change means that you’ve exited your virtual environment. If you interact with Python or pip now, you’ll interact with your globally configured Python environment.

If you want to go back into a virtual environment that you’ve created before, you again need to run the activate script of that virtual environment.

If the name shows up, then you know that your virtual environment is active, and you can install your external dependencies. If you don’t see the name in your command prompt, remember to activate your Python virtual environment before installing any packages.

At this point, you’ve covered the essentials of working with Python virtual environments. If that’s all you need, then happy trails as you continue creating!

However, if you want to know what exactly just happened, why so many tutorials ask you to create a virtual environment in the first place, and what a Python virtual environment really is, then keep on reading! You’re about to go deep!

Why Do You Need Virtual Environments?

Nearly everyone in the Python community suggests that you use virtual environments for all your projects. But why? If you want to find out why you need to set up a Python virtual environment in the first place, then this is the right section for you.

The short answer is that Python isn’t great at dependency management. If you’re not specific, then pip will place all the external packages that you install in a folder called site-packages/ in your base Python installation.

Deep Dive: site-packages Show/Hide

Technically, Python comes with two site-packages folders:

You can find these folders in different locations if you’re working on Fedora or RedHat Linux distributions.

However, most operating systems implement Python’s site-packages setting so that both locations point to the same path, effectively creating a single site-packages folder.

You can check the paths using sysconfig :

Most likely, both outputs will show you the same path. If both outputs are the same, then your operating system doesn’t put purelib modules into a different folder than platlib modules. If two different paths show up, then your operating system makes this distinction.

Even if your operating system distinguishes between the two, dependency conflicts will still arise because all purelib modules will go into a single location for purelib modules, and the same will happen with the platlib modules.

To work with virtual environments, you don’t need to worry about the implementation detail of a single site-packages folder or two separate ones. In fact, you probably won’t ever need to think about it again. If you want to, however, you can keep in mind that when someone mentions Python’s site-packages directory, they could be talking about two different directories.

Several issues can come up if all of your external packages land in the same folder. In this section, you’ll learn more about them, as well as other problems that virtual environments mitigate.

Avoid System Pollution

Linux and macOS come preinstalled with a version of Python that the operating system uses for internal tasks.

If you install packages to your operating system’s global Python, these packages will mix with the system-relevant packages. This mix-up could have unexpected side effects on tasks crucial to your operating system’s normal behavior.

Additionally, if you update your operating system, then the packages you installed might get overwritten and lost. You don’t want either of those headaches to happen!

Sidestep Dependency Conflicts

One of your projects might require a different version of an external library than another one. If you have only one place to install packages, then you can’t work with two different versions of the same library. This is one of the most common reasons for the recommendation to use a Python virtual environment.

To better understand why this is so important, imagine you’re building Django websites for two different clients. One client is comfortable with their existing web app, which you initially built using Django 2.2.26, and that client refuses to update their project to a modern Django version. Another client wants you to include async functionality in their website, which is only available starting from Django 4.0.

If you installed Django globally, you could only have one of the two versions installed:

If you install two different versions of the same package into your global Python environment, the second installation overwrites the first one. For the same reason, having a single virtual environment for both clients won’t work either. You can’t have two different versions of the same package in a single Python environment.

Looks like you won’t be able to work on one of the two projects with this setup! However, if you create a virtual environment for each of your clients’ projects, then you can install a different version of Django into each of them:

If you now activate either of the two virtual environments, then you’ll notice that it still holds its own specific version of Django. The two environments also have different dependencies, and each only contains the dependencies necessary for that version of Django.

With this setup, you can activate one environment when you work on one project and another when you work on another. Now you can keep any number of clients happy at the same time!

Minimize Reproducibility Issues

If all your packages live in one location, then it’ll be difficult to only pin dependencies that are relevant for a single project.

If you’ve worked with Python for a while, then your global Python environment might already include all sorts of third-party packages. If that’s not the case, then pat yourself on the back! You’ve probably installed a new version of Python recently, or you already know how to handle virtual environments to avoid system pollution.

To clarify what reproducibility issues you can encounter when sharing a Python environment across multiple projects, you’ll look into an example situation next. Imagine you’ve worked on two independent projects over the past month:

Unaware of virtual environments, you installed all necessary packages into your global Python environment:

Your Flask app has turned out to be quite helpful, so other developers want to work on it as well. They need to reproduce the environment that you used for working on it. You want to go ahead and pin your dependencies so that you can share your project online:

Which of these packages are relevant for your Flask app, and which ones are here because of your web scraping project? It’s hard to tell when all external dependencies live in a single bucket.

With a single environment like this one, you’d have to manually go through the dependencies and know which are necessary for your project and which aren’t. At best, this approach is tedious, but more likely, it’s error prone.

If you use a separate virtual environment for each of your projects, then it’ll be more straightforward to read the project requirements from your pinned dependencies. That means you can share your success when you develop a great app, making it possible for others to collaborate with you!

Dodge Installation Privilege Lockouts

Finally, you may need administrator privileges on a computer to install packages into the host Python’s site-packages directory. In a corporate work environment, you most likely won’t have that level of access to the machine that you’re working on.

If you use virtual environments, then you create a new installation location within the scope of your user privileges, which allows you to install and work with external packages.

Whether you’re coding as a hobby on your own machine, developing websites for clients, or working in a corporate environment, using a virtual environment will save you lots of grief in the long run.

What Is a Python Virtual Environment?

At this point, you’re convinced that you want to work with virtual environments. Great, but what are you working with when you use a virtual environment? If you want to understand what Python virtual environments are, then this is the right section for you.

The short answer is that a Python virtual environment is a folder structure that gives you everything you need to run a lightweight yet isolated Python environment.

A Folder Structure

When you create a new virtual environment using the venv module, Python creates a self-contained folder structure and copies or symlinks the Python executable files into that folder structure.

You don’t need to dig deeply into this folder structure to learn more about what virtual environments are made of. In just a bit, you’ll carefully scrape off the topsoil and investigate the high-level structures that you uncover.

However, if you’ve already got your shovel ready and you’re itching to dig, then open the collapsible section below:

Virtual environment folder structure Show/Hide

Welcome, brave one. You’ve accepted the challenge to venture deeper into your virtual environment’s folder structure! In this collapsible section, you’ll find instructions on how to take a look into that dark abyss.

On your command line, navigate to the folder that contains your virtual environment. Take a deep breath and brace yourself, then execute the tree command to display all the contents of the directory:

The tree command displays the content of your venv directory in a very long tree structure.

Note: Alternatively, you could hone your skills by creating a new virtual environment, installing the rptree package into it, and using that to display the folder’s tree structure. You could even take a bigger detour and build that directory tree generator yourself!

However you end up displaying all the contents of the venv/ folder, you might be surprised what you find. Many developers experience a slight shock when they first take a peek. There are a lot of files in there!

If this was your first time and you felt that way, then welcome to the group of people who have taken a look and gotten overwhelmed.

A virtual environment folder contains a lot of files and folders, but you might notice that most of what makes this tree structure so long rests inside the site-packages/ folder. If you trim down the subfolders and files in there, you end up with a tree structure that isn’t too overwhelming:

This reduced tree structure gives you a better overview of what’s going on in your virtual environment folder:

Include\ is an initially empty folder that Python uses to include C header files for packages you might install that depend on C extensions.

Lib\ contains the site-packages\ folder, which is one of the main reasons for creating your virtual environment. This folder is where you’ll install external packages that you want to use within your virtual environment. By default, your virtual environment comes preinstalled with two dependencies, pip and setuptools. You’ll learn more about them in a bit.

pyvenv.cfg is a crucial file for your virtual environment. It contains only a couple of key-value pairs that Python uses to set variables in the sys module that determine which Python interpreter and which site-packages directory the current Python session will use. You’ll learn more about the settings in this file when you read about how a virtual environment works.

include/ is an initially empty folder that Python uses to include C header files for packages you might install that depend on C extensions.

lib/ contains the site-packages/ directory nested in a folder that designates the Python version ( python3.10/ ). site-packages/ is one of the main reasons for creating your virtual environment. This folder is where you’ll install external packages that you want to use within your virtual environment. By default, your virtual environment comes preinstalled with two dependencies, pip and setuptools. You’ll learn more about them in a bit.

lib64/ in many Linux systems comes as a symlink to lib/ for compatibility reasons. Some Linux systems may use the distinction between lib/ and lib64/ to install different versions of libraries depending on their architecture.

pyvenv.cfg is a crucial file for your virtual environment. It contains only a couple of key-value pairs that Python uses to set variables in the sys module that determine which Python interpreter and which site-packages directory the current Python session will use. You’ll learn more about the settings in this file when you read about how a virtual environment works.

include/ is an initially empty folder that Python uses to include C header files for packages you might install that depend on C extensions.

lib/ contains the site-packages/ directory nested in a folder that designates the Python version ( python3.10/ ). site-packages/ is one of the main reasons for creating your virtual environment. This folder is where you’ll install external packages that you want to use within your virtual environment. By default, your virtual environment comes preinstalled with two dependencies, pip and setuptools. You’ll learn more about them in a bit.

pyvenv.cfg is a crucial file for your virtual environment. It contains only a couple of key-value pairs that Python uses to set variables in the sys module that determine which Python interpreter and which site-packages directory the current Python session will use. You’ll learn more about the settings in this file when you read about how a virtual environment works.

From this bird’s-eye view of the contents of your virtual environment folder, you can zoom out even further to discover that there are three essential parts of a Python virtual environment:

The installed packages inside site-packages/ are optional but come as a reasonable default. However, your virtual environment would still be a valid virtual environment if this directory were empty, and there are ways to create it without installing any dependencies.

You can double-check that Python installed both pip and setuptools into your virtual environment by using pip list :

Your version numbers may differ, but this output confirms that Python installed both packages when you created the virtual environment with its default settings.

Note: Below that output, pip might also display a warning that you’re not using the latest version of the module. Don’t worry about it yet. Later, you’ll learn more about why this happens and how to automatically update pip when creating your virtual environment.

These two installed packages make up most of the content of your new virtual environment. However, you’ll notice that there are also a couple of other folders in the site-packages/ directory:

The .dist-info/ directories for pip and setuptools contain package distribution information that exists to record information about installed packages.

Note: You’re learning about these additional files and folders for the sake of completeness. You won’t need to remember them to effectively work with your virtual environments. It’s enough to keep in mind that any preinstalled packages in your site-packages/ directory are standard tools that make installing other packages more user-friendly.

At this point, you’ve seen all the files and folders that make up a Python virtual environment if you’ve installed it using the built-in venv module.

Keep in mind that your virtual environment is just a folder structure, which means that you can delete and re-create it anytime you want to. But why this specific folder structure, and what does it make possible?

An Isolated Python Installation

Python virtual environments aim to provide a lightweight, isolated Python environment that you can quickly create and then discard when you don’t need it anymore. The folder structure that you’ve seen above makes that possible by providing three key pieces:

You want to achieve an isolated environment so that any external packages you install won’t conflict with global site-packages. What venv does to make this possible is to reproduce the folder structure that a standard Python installation creates.

This structure accounts for the location of the copy or symlink of the Python binary and the site-packages directory, where Python installs external packages.

Note: Whether or not the Python executable in your virtual environment is a copy or a symlink of the Python executable that you’ve based the environment on depends primarily on your operating system.

Windows and Linux may create symlinks instead of copies, while macOS always creates a copy. You can try to influence the default behavior with optional arguments when creating the virtual environment. However, you won’t have to worry about it in most standard cases.

In addition to the Python binary and the site-packages directory, you get the pyvenv.cfg file. It’s a small file that contains only a couple of key-value pairs. However, these settings are crucial for making your virtual environment work:

You’ll learn more about this file in a later section when reading about how a virtual environment works.

Suppose you closely inspect your newly minted virtual environment’s folder structure. In that case, you might notice that this lightweight installation doesn’t contain any of the trusted standard library modules. Some might say that Python without its standard library is like a toy car without batteries!

However, if you start the Python interpreter from within your virtual environment, then you can still access all the goodies from the standard library:

In the example code snippet above, you’ve successfully imported both the urllib module and the pp() shortcut from the pretty print module. Then you used dir() to inspect the urllib module.

Both modules are part of the standard library, so how come you have access to them even though they’re not in the folder structure of your Python virtual environment?

You can access Python’s standard library modules because your virtual environment reuses Python’s built-ins and the standard library modules from the Python installation from which you created your virtual environment. In a later section, you’ll learn how the virtual environment achieves linking to your base Python’s standard library.

Note: Because you always need an existing Python installation to create your virtual environment, venv opts to reuse the existing standard library modules to avoid the overhead of copying them into your new virtual environment. This intentional decision speeds up the creation of virtual environments and makes them more lightweight, as described in the motivation for PEP 405.

In addition to the standard library modules, you can optionally give your virtual environment access to the base installation’s site-packages through an argument when creating the environment:

This connection works in only one direction. Even if you give your virtual environment access to the source Python’s site-packages folder, any new packages you install into your virtual environment won’t mingle with the packages there. Python will respect the isolated nature of installations to your virtual environment and place them into the separate site-packages directory within the virtual environment.

You know that a Python virtual environment is just a folder structure with a settings file. It might or might not come with pip preinstalled, and it has access to the source Python’s site-packages directory while remaining isolated. But you might wonder how all of this works.

How Does a Virtual Environment Work?

If you know what a Python virtual environment is but wonder how it manages to create the lightweight isolation it provides, then you’re in the right section. Here you’ll learn how the folder structure and the settings in your pyvenv.cfg file interact with Python to provide a reproducible and isolated space for installing external dependencies.

It Copies Structure and Files

If you locate your system-wide Python installation on your operating system and inspect the folder structure there, then you’ll see that your virtual environment resembles that structure.

Note: On Windows, you may notice that python.exe in your base Python installation isn’t in Scripts\ but is one folder level up. In your virtual environment, the executable is intentionally located in the Scripts\ folder.

This small change to the folder structure means that you only need to add a single directory to your shell PATH variable to activate the virtual environment.

While you might find some additional files and folders in your base Python installation, you’ll notice that the standard folder structure is the same as in your virtual environment. venv creates this folder structure to assure that Python will work as expected in isolation, without the need to apply many additional changes.

It Adapts the Prefix-Finding Process

With the standard folder structure in place, the Python interpreter in your virtual environment can understand where all relevant files are located. It does this with only minor adaptations to its prefix-finding process according to the venv specification.

Instead of looking for the os module to determine the location of the standard library, the Python interpreter first looks for a pyvenv.cfg file. If the interpreter finds this file and it contains a home key, then the interpreter will use that key to set the value for two variables:

If the interpreter doesn’t find a pyvenv.cfg file, then it determines that it’s not running within a virtual environment, and both sys.base_prefix and sys.prefix will then point to the same path.

Exercise: Explore Prefix Paths Show/Hide

You can confirm that this works as described. Spin up a Python interpreter within an active virtual environment and inspect both variables:

You can see that the variables point to different locations on your system.

Now go ahead and deactivate the virtual environment, enter a new interpreter session, and rerun the same code:

You should see that both sys.prefix and sys.base_prefix now point to the same path.

If these two variables have different values, then Python adapts where it’ll look for modules:

The site and sysconfig standard-library modules are modified such that the standard library and header files are found relative to sys.base_prefix […], while site-package directories […] are still found relative to sys.prefix […]. (Source)

This change effectively allows the Python interpreter in your virtual environment to use the standard library modules from your base Python installation while pointing to its internal site-packages directory to install and access external packages.

It Links Back to Your Standard Library

Python virtual environments aim to be a lightweight way to provide you with an isolated Python environment that you can quickly create and then delete when you don’t need it anymore. To make this possible, venv copies only the minimally necessary files:

[A] Python virtual environment in its simplest form would consist of nothing more than a copy or symlink of the Python binary accompanied by a pyvenv.cfg file and a site-packages directory. (Source)

The Python executable in your virtual environment has access to the standard library modules of the Python installation on which you based the environment. Python makes this possible by pointing to the file path of the base Python executable in the home setting in pyvenv.cfg :

If you navigate to the path value of the highlighted line in pyvenv.cfg and list the contents of the folder, then you find the base Python executable that you used to create your virtual environment. From there, you can navigate to find the folder that contains your standard library modules:

The paths that your Python session has access to in sys.path determine which locations Python can import modules from.

If you activate your virtual environment and enter a Python interpreter, then you can confirm that the path to the standard library folder of your base Python installation is available:

It Modifies Your PYTHONPATH

If you inspect that variable without an active virtual environment, you’ll see the default path locations for your default Python installation:

However, if you activate your virtual environment before starting another interpreter session and rerun the same commands, then you’ll get different output:

Python replaced the default site-packages directory path with the one that lives inside your virtual environment. This change means that Python will load any external packages installed in your virtual environment. Conversely, because the path to your base Python’s site-packages directory isn’t in this list anymore, Python won’t load modules from there.

This change in Python’s path settings effectively creates the isolation of external packages in your virtual environment.

Optionally, you can get read-only access to the system site-packages directory of your base Python installation by passing an argument when creating the virtual environment.

It Changes Your Shell PATH Variable on Activation

For convenience, you’ll usually activate your virtual environment before working in it, even though you don’t have to.

To activate your virtual environment, you need to execute an activation script:

Which activation script you’ll have to run depends on your operating system and the shell that you’re using.

If you dig into your virtual environment’s folder structure, then you’ll find a few different activation scripts that it ships with:

These activation scripts all have the same purpose. However, they need to provide different ways of achieving it because of the various operating systems and shells that users are working with.

Note: You can open any of the highlighted files in your favorite code editor to inspect the content of a virtual environment activation script. Feel free to dig into that file to get a deeper understanding of what it does, or keep reading to quickly get the gist of it.

Two critical actions happen in the activation script:

These changes put the convenience of virtual environments into effect within your shell:

Both of these changes are minor adaptations that exist purely for your convenience. They aren’t strictly necessary, but they make working with Python virtual environments more enjoyable.

You can inspect your PATH variable before and after activation of your virtual environment. If you’ve activated your virtual environment, then you’ll see the path to the folder containing your internal executables at the beginning of PATH :

Keep in mind that the output of printing your PATH variable will most likely look quite different. The important point is that the activation script has added the path to your virtual environment at the beginning of the PATH variable.

Give it a try and inspect the changes. This small change to your PATH variable gives you the convenience of running executables in your virtual environment without the need to provide the absolute path.

It Runs From Anywhere With Absolute Paths

You don’t need to activate your virtual environment to use it. You can work with your virtual environment without activating it, even though activating it is a common action that you’ll often see recommended.

If you provide only the name of an executable to your shell, it’ll look through the location recorded in PATH for an executable file sporting that name. It’ll then pick and run the first one that matches that criterion.

The activation script changes your PATH variable so that the binaries folder of your virtual environment is the first place your shell looks for executables. This change allows you to type only pip or python to run the respective programs situated inside your virtual environment.

If you don’t activate your virtual environment, then you can instead pass the absolute path of the Python executable inside your virtual environment to run any script from within your virtual environment:

Exercise: Comprehension Check Show/Hide

Take some notes of possible ways to check, then try out some of the solutions mentioned in the Solution block below.

Solution: Comprehension Check Show/Hide

As described in previous sections of this tutorial, you could:

If you’re unsure why any of these approaches could confirm that this works as described, follow the links to the relevant sections in this tutorial to refresh your memory.

You’ll often activate your virtual environment before working with it and deactivate it after you’re done. However, there is an everyday use case where using the absolute paths is a helpful approach.

Note: Absolute paths can be helpful for running a scheduled script on your remote server or in a Docker container. Specifically, you’ll want to use absolute paths if the script requires external dependencies that you want to isolate from the rest of your server in a Python virtual environment.

Embedding the activation of your virtual environment in your script is a fussy exercise that goes wrong more often than it doesn’t. Instead, equipped with the knowledge that you’ve gained in this tutorial, you can use the absolute path to the Python interpreter in your virtual environment when running your script.

You could use this, for example, if you were setting up an hourly CRON job on your remote Linux server that checks for site connectivity asynchronously using the external aiohttp package that you installed in a virtual environment:

You don’t need to fiddle with activating your virtual environment to use the right Python interpreter that has access to the dependencies that you’ve installed inside the virtual environment. Instead, you just pass the absolute path to the binary of that interpreter. Python takes care of the rest for you during initialization.

As long as you provide the absolute path to your Python executable, you don’t need to activate your virtual environment to enjoy the benefits of using one.

How Can You Customize a Virtual Environment?

Change the Command Prompt

You can change the folder name that contains your virtual environment when you create it by passing a name other than venv. In fact, you’ll often see different names in different projects. Some of them are commonly used:

You could name the folder that you create for your virtual environment anything you want.

Whatever name you choose will show up in your command prompt after you activate the virtual environment:

If you give your virtual environment folder an alternate name, you’ll also need to consider that name when you want to run your activation script, as shown in the code example above.

Overwrite Existing Environments

Before you try that out, it’s helpful to see that running the command to create a new virtual environment without this argument won’t overwrite an existing virtual environment with the same name:

In this code example, you first created a virtual environment called venv, then used the environment-internal pip executable to install requests into the site-packages directory of your virtual environment. You then used pip list to confirm that it had been installed, together with its dependencies.

Note: You ran all these commands without activating the virtual environment. Instead, you used the absolute path to the internal pip executable to install into your virtual environment. Alternatively, you could’ve activated the virtual environment.

In the highlighted line, you attempted to create another virtual environment using the same name, venv.

You might expect venv to notify you that there’s an existing virtual environment on the same path, but it doesn’t. You might expect venv to automatically delete the existing virtual environment with the same name and replace it with a new one, but it doesn’t do that either. Instead, when venv finds an existing virtual environment of the same name on the path you provided, it doesn’t do anything—and again, it doesn’t communicate this to you.

If you list the installed packages after running the virtual environment creation command a second time, then you’ll notice that requests and its dependencies still show up. This might not be what you want to achieve.

You then confirmed that Python automatically discarded the existing virtual environment with the same name and created a new default virtual environment without the previously installed packages.

Create Multiple Virtual Environments at Once

If one virtual environment isn’t enough, you can create multiple separate virtual environments in one go by passing more than one path to the command:

Running this command creates two separate virtual environments in two different locations. These two folders are independent virtual environment folders. Passing more than one path therefore just saves you the effort of typing the creation command more than once.

You don’t have to do this. Instead, you could provide an absolute path that points anywhere on your system. If any of your path directories don’t yet exist, venv will create them for you.

You’re also not limited to creating two virtual environments at once. You can pass as many valid paths as you want, separated by a whitespace character. Python will diligently set up a virtual environment at each location, even creating any missing folders on the way.

Update the Core Dependencies

It can be frustrating to create something new just to see that it’s already outdated! Why does this happen?

The installation of pip that you’ll receive when creating a virtual environment with the default configuration of venv is likely outdated because venv uses ensurepip to bootstrap pip into your virtual environment.

ensurepip intentionally doesn’t connect to the Internet, but instead uses a pip wheel that comes bundled with each new CPython release. Therefore, the bundled pip has a different update cycle than the independent pip project.

While using the bootstrapped version of pip can be helpful in some cases, you might want to have the latest pip to avoid potential security issues or bugs that might still be around in an older version. For an existing virtual environment, you can follow the instructions that pip prints to your terminal and use pip to upgrade itself.

Avoid Installing pip

Your virtual environment still does everything that qualifies it as a virtual environment by providing lightweight isolation with a separate Python executable.

might still seem to work. Don’t do this, though, because running the command won’t give you what you’re looking for. You’d be using a pip executable from somewhere else on your system, and your package will land in the site-packages folder of whichever Python installation is associated with that pip executable.

To work with a virtual environment that doesn’t have pip installed, you can manually install packages into your site-packages directory or place your ZIP files in there then import them using Python ZIP imports.

Include the System Site-Packages

In some situations, you might want to keep access to your base Python’s site-packages directory instead of severing that tie. For example, you might have already set up a package that’s compiled during installation, such as Bokeh, in your global Python environment.

Bokeh happens to be your data exploration library of choice, and you use it for all your projects. You still want to keep your clients’ projects in separate environments, but installing Bokeh into each of these can take a couple of minutes each. For quick iteration, you instead want to have access to the existing Bokeh installation without needing to redo it for every virtual environment you create.

Note: If you install any additional external packages, then Python will put them into the site-packages directory of your virtual environment. You only get read access to the system site-packages directory.

Copy or Link Your Executables

Whether you receive a copy or a symlink of your Python binaries depends on the operating system that you’re working with:

PEP 405 mentions the advantages of creating symlinks:

Symlinking is preferable where possible because, in the case of an upgrade to the underlying Python installation, a Python executable copied in a venv might become out-of-sync with the installed standard library and require manual upgrade. (Source)

While it can be helpful to symlink the executables so that they’ll automatically stay in sync even if you upgrade your base Python installation, the added flimsiness of this approach may outweigh its benefit. For example, when you double-click python.exe in Windows, the operating system will eagerly resolve the symlink and ignore your virtual environment.

Most likely, you won’t ever have to touch these arguments, but if you have a good reason for attempting to force either symlinks or copies over your operating system’s default, then you can do so:

You can pass either one of these optional arguments when creating your virtual environment.

Upgrade Your Python to Match the System Python

If you’ve built your virtual environment using copies rather than symlinks and later updated your base Python version on your operating system, you might run into a version mismatch with standard library modules.

If you run this command and you’ve updated your Python version since initially creating the virtual environment, then you’ll keep your installed libraries, but venv will update the executables for pip and Python.

In this section, you’ve learned that you can apply a lot of customization to the virtual environments that you build with the venv module. These adaptations can be pure convenience updates, such as naming your command prompt differently from your environment folder, overwriting existing environments, or creating multiple environments with a single command. Other customizations create different functionality in your virtual environments by, for example, skipping the installation of pip and its dependencies, or linking back to the base Python’s site-packages folder.

But what if you want to do even more than that? In the next section, you’ll explore alternatives to the built-in venv module.

The venv module is a great way to work with Python virtual environments. One of its main advantages is that venv comes preinstalled with Python starting from version 3.3. But it isn’t the only option you have. You can use other tools to create and handle virtual environments in Python.

In this section, you’ll learn about two popular tools. They have different scopes but are both also commonly used for the same purpose as the venv module:

The Virtualenv Project

Virtualenv is a tool that was specifically made for creating isolated Python environments. It’s been a long-time favorite within the Python community and precedes the built-in venv module.

Any of these additional functionalities can come in handy when you’re working on your Python projects. You might even want to save a blueprint of your virtualenv in code together with your project to aid reproducibility. Virtualenv has a rich programmatic API that allows you to describe virtual environments without creating them.

After installing virtualenv on your system, you can create and activate a new virtual environment similarly to how you do it using venv :

Note: You might notice that virtualenv creates the isolated environment much more quickly than the built-in venv module, which is possible because the tool caches platform-specific application data which it can quickly read from.

There are two main user advantages with virtualenv over venv :

Note: If you want to try working with virtualenv, but you don’t have the permissions to install it, you can use Python’s zipapp module to circumvent that. Follow the instructions in the docs on installing virtualenv via zipapp.

If you’re just getting started with virtual environments in Python, then you may want to stick with the built-in venv module. However, if you’ve used it for a while and you’re bumping into the tool’s limitations, then it’s a great idea to get started using virtualenv.

The Conda Package and Environment Manager

Conda gives you an alternative package and environment management approach. While the tool is primarily associated with the data science community and the Anaconda Python distribution, its potential use cases extend beyond that community and beyond just installing Python packages:

Package, dependency and environment management for any language—Python, R, Ruby, Lua, Scala, Java, JavaScript, C/ C++, FORTRAN, and more. (Source)

While you can also use conda to set up an isolated environment to install Python packages, this is only one feature of the tool:

pip installs python packages within an environment; conda installs any package within conda environments. (Source)

As you may gather from this quote, conda accomplishes this isolation differently from the venv module and virtualenv project.

Note: A complete discussion of the conda package and environment manager is outside the scope of this tutorial. You’ll gloss over the differences and look at conda specifically for creating and working with a Python virtual environment.

In its default configuration, conda get its packages from repo.anaconda.com instead of PyPI. This alternative package index is maintained by the Anaconda project and is similar PyPI, but not identical.

If you’re working in the data science space and with Python alongside other data science projects, then conda is an excellent choice that works across platforms and languages.

After installing Anaconda or Miniconda, you can create a conda environment:

Suppose your standard PowerShell session doesn’t recognize the conda command after successfully installing Anaconda. In that case, you can look for the Anaconda PowerShell Prompt in your programs and work with that one instead.

This command creates a new conda environment in a central location on your computer.

To work within your new conda environment, you’ll need to activate it:

After activating the environment, you can install packages from conda’s package repository into that environment:

The install command installs a third-party package from conda’s package repository into your active conda environment.

When you’re done working in the environment, you’ll have to deactivate it:

If you only have pure-Python dependencies and you haven’t worked with Anaconda before, then you’re better off using the more lightweight venv module directly or giving virtualenv a try.

How Can You Manage Your Virtual Environments?

If you’ve absorbed all the information from the previous sections, but you’re unsure how to handle the multitude of environment folders that have started agglomerating on your system, keep reading here.

In this section, you’ll learn how to extract the essential information of your virtual environment into a single file so that you can quickly delete and re-create your virtual environment folder at any time and on any computer.

You’ll also learn about two different ways of organizing where to keep your virtual environment folders and about some popular third-party tools that can help you manage your virtual environments.

Decide Where to Create Your Environment Folders

A Python virtual environment is just a folder structure. You can place it anywhere on your system. However, a consistent structure can help, and there are two prominent opinions on where to create your virtual environment folders:

Both of these have merits and disadvantages, and your preference will ultimately depend on your workflow.

In the project-folder approach approach, you create a new virtual environment in the root folder of the project that’ll use this virtual environment for:

The virtual environment folder then lives side by side with any code that you’ll write for that project.

This structure has the advantage that you’ll know which virtual environment belongs to which project, and you can activate your virtual environment using a short relative path once you’ve navigated into the project folder.

In the single-folder approach, you keep all your virtual environments in a single folder, for example in a subfolder of your home directory:

If you use this approach, it could be less effort to keep track of which virtual environments you’ve created. You can go to a single location on your operating system to inspect all virtual environments and decide which ones to keep and which ones to delete.

On the other hand, you won’t be able to activate your virtual environment quickly using a relative path when you’ve already navigated to your project folder. Instead, it’s best to activate it using the absolute path to the activate script in the respective virtual environment folder.

Note: You can use either of the two approaches and even mix and match.

You could create your virtual environments anywhere on your system. Just keep in mind that a clear structure will make it more user-friendly for you to know where to find the folders.

A third option is to leave this decision to your integrated development environment (IDE). Many of these programs include options to automatically create a virtual environment for you when you start a new project.

To learn more about how your favorite IDE handles virtual environments, check out its online documentation on the topic. For example, VS Code and PyCharm have their own approaches to creating virtual environments.

Treat Them as Disposables

Virtual environments are disposable folder structures that you should be able to safely delete and re-create at any time without losing information about your code project.

You also shouldn’t commit your virtual environment to version control, and you shouldn’t ship it with your project.

Because virtual environments aren’t entirely self-sufficient Python installations but rely on the base Python’s standard library, you won’t create a portable application by distributing your virtual environment together with your code.

Note: If you want to learn how to distribute your Python project, then you can read about publishing an open-source package to PyPI or using PyInstaller to distribute Python applications.

Virtual environments are meant to be lightweight, disposable, and isolated environments to develop your projects in.

However, you should be able to re-create your Python environment on a different computer so that you can run your program or continue developing it there. How can you make that happen when you treat your virtual environment as disposable and won’t commit it to version control?

Pin Your Dependencies

To make your virtual environment reproducible, you need a way to describe its contents. The most common way to do this is by creating a requirements.txt file while your virtual environment is active:

This list is a recipe for pip to know which version of which package to install. As long as you keep this requirements.txt file up to date, you can always re-create the virtual environment that you’re working in, even after deleting the venv/ folder or moving to a different computer altogether:

Note: By committing your requirements.txt file to version control, you can ship your project code with the recipe that allows your users and collaborators to re-create the same virtual environment on their machines.

Keep in mind that while this is a widespread way to ship dependency information with a code project in Python, it isn’t deterministic:

You can’t easily solve either of these issues with requirements.txt alone, but many third-party dependency management tools attempt to address them to guarantee deterministic builds:

Projects that integrate the virtual environment workflow into their features but go beyond that will also often include ways to create lock files that allow deterministic builds of your environments.

Avoid Virtual Environments in Production

You might wonder how to include and activate your virtual environment when deploying a project to production. In most cases, you don’t want to include your virtual environment folder in remote online locations:

You still want isolated environments and reproducibility for your code projects. You’ll achieve that by pinning your dependencies instead of including the virtual environment folder that you’ve worked with locally.

Most remote hosting providers, including CI/CD pipeline tools and Platform-as-a-Service (PaaS) providers, such as Heroku or Google App Engine (GAE), will automatically create that isolation for you.

When you push your code project to one of these hosted services, the service will often allocate a virtual fraction of a server to your application. Such virtualized servers are isolated environments by design, which means that your code will run in its separate environment by default.

In most hosted solutions, you won’t have to deal with creating the isolation, but you’ll still need to provide the information about what to install in the remote environment. For this, you’ll often use the pinned dependencies in your requirements.txt file.

Note: If you run multiple projects on a server that you host yourself, then you might benefit from setting up virtual environments on that server.

In that case, you’ll get to treat the server similarly to your local computer. Even then, you won’t copy the virtual environment folder. Instead, you’ll re-create the virtual environment on your remote server from your pinned dependencies.

Most hosted platform providers will also ask you to create a settings file specific to the tool that you’re working with. This file will include information that isn’t recorded in requirements.txt but that the platform needs to set up a functioning environment for your code. You’ll need to read up on these specific files in the documentation of the hosting service that you’re planning to use.

A popular option that takes virtualization to the next level and still allows you to create a lot of the setup yourself is Docker.

Use Third-Party Tools

The Python community has created many additional tools that use virtual environments as one of their features and allow you to manage multiple virtual environments in a user-friendly manner.

Because many tools come up in online discussions and tutorials, you might wonder what each of them is about and how they can help you manage your virtual environments.

While discussing each of them is out of the scope of this tutorial, you’ll get an overview of which popular projects exist, what they do, and where you can learn more:

virtualenvwrapper is an extension to the virtualenv project that makes creating, deleting, and otherwise managing virtual environments lower effort. It keeps all your virtual environments in one place, introduces user-friendly CLI commands for managing and switching between virtualenvs, and is also configurable and extensible. virtualenvwrapper-win is a Windows port of this project.

Poetry is a tool for Python dependency management and packaging. With Poetry, you can declare packages that your project depends on, similar to requirements.txt but deterministic. Poetry will then install these dependencies in an auto-generated virtual environment and help you manage your virtual environment.

Pipenv aims to improve packaging in Python. It creates and manages virtual environments for your projects using virtualenv in the back. Like Poetry, Pipenv aims to improve dependency management to allow for deterministic builds. It’s a relatively slow, high-level tool that has been supported by the Python Packaging Authority (PyPA).

pipx allows you to install Python packages that you’d habitually run as stand-alone applications in isolated environments. It creates a virtual environment for each tool and makes it globally accessible. Aside from helping with code quality tools such as black, isort, flake8, pylint, and mypy, it’s also useful for installing alternative Python interpreters, such as bpython, ptpython, or ipython.

pipx-in-pipx is a wrapper you can use for installing pipx that takes the recursive acronym for pip to the next level by allowing you to install and manage pipx using pipx itself.

pyenv isn’t inherently related to virtual environments, even though it’s often mentioned in relation to this concept. You can manage multiple Python versions with pyenv, which allows you to switch between a new release and an older Python version that you need for a project you’re working on. pyenv also has a Windows port called pyenv-win.

pyenv-virtualenv is a plugin for pyenv that combines pyenv with virtualenv, allowing you to create virtual environments for the pyenv-managed Python versions on UNIX systems. There’s even a plugin to mix pyenv with virtualenvwrapper, called pyenv-virtualenvwrapper.

The Python community built a whole host of third-party projects that can help you manage your Python virtual environments in a user-friendly manner.

Remember that these projects are meant to make the process more convenient for you and aren’t necessary for working with virtual environments in Python.

Conclusion

Congratulations on making it through this tutorial on Python virtual environments. Throughout the tutorial, you built a thorough understanding of what virtual environments are, why you need them, how they function internally, and how you can manage them on your system.

In this tutorial, you learned how to:

Next time a tutorial tells you to create and activate a virtual environment, you’ll better understand why that’s a good suggestion and what Python does for you behind the scenes.

Take the Quiz: Test your knowledge with our interactive “Python Virtual Environments: A Primer” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Working With Python Virtual Environments

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

About Martin Breuss

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Martin likes automation, goofy jokes, and snakes, all of which fit into the Python community. He enjoys learning and exploring and is up for talking about it, too. He writes and records content for Real Python and CodingNomads.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Master Real-World Python Skills With Unlimited Access to Real Python

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Creating a Python Virtual Environment in Windows

In the last tutorial we have discussed about how to install python in a windows operating system.

Today We’ll learn how to create a virtual environment, If you don’t know what virtual environment is, let me explain it to you.

Think of virtual environment as a room in your house, you can do whatever you want in one room without affecting the other rooms. Similarly when you install software packages in a computer one software’s dependency may affect the others and cause some conflicts.

Example: Installing Anaconda and Tensorflow in the same machine without any virtual environment may cause version conflicts because Tensorflow runs on newer version of a package and Anaconda uses the same package but an older version.

So, How to overcome this problem? That’s the point of this journey. Creating a virtual environment.

First I’ll demonstrate how it works, then we’ll go through the steps on achieving it.

When I run the command “pip list” in my command prompt it shows me the python packages that I have installed, as you can see it is just default packages that comes with pip and python

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Once I activate my virtual environment named “venv-win” (virtual environment windows) You can name it whatever you want, I’ll run the same “pip list” command and look at the output now

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

OMG! Where did it come from, this is the beauty of virtual environment so let’s create one

Step 1: Installing virtualenv through pip

If you have already setup python as I have taught you in the previous story on how to setup python in windows then you are good to go, If not make sure you know what you are doing or go back and read the previous story and then comeback.

run the command “ pip install virtualenv” in your command prompt

Make sure you have internet connected, pip collects required packages from the internet and installs it on your machine. Once you see the message virtualenv installed go to next step.

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Step 2: Creating a virtualenv

Once you have virtualenv installed, navigate to the directory where you want to create your virtual environment, just make sure it is easily accessible.

I personally have all my programming docs under the folder called Workspace in my D:\ drive, You can create the environment where ever you want. just imagine replacing my folder names with your folder’s name.

Navigate to your desired folder by opening “This PC” or File Explorer and move on the next step.

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

To open command prompt from the current folder follow the following steps 😉

Click on the address bar in the File Explorer

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Once you click on the address bar it will show your current path highlighted.

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Press Backspace or Delete key to clear it and then type “cmd” and hit enter

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

You will see a command prompt window with the directory “D:\Workspace” in my case, In your machine you will see the path of the directory from which you have opened cmd (ie) D: or E: followed by a slash (\) and then the folder name of your choice

Enter the command “virtualenv ”

make sure you are now working in the command prompt that just popped up by executing the previous step. I have named my virtualenv as “myenv”.

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Once you hit enter you might see something like this

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Be patient while running this command, It takes some time to create a environment (30 seconds to a minute), Do not panic if see just cursor blinking in command prompt, remember be patient.

Making sure we have installed it properly

Open the folder in file explorer where you have intended to create a virtual environment and you should see a folder named “myenv” or the name your virtual environment show up

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Step 3: Activating the virtual environment created

To activate the environment let’s understand which file activates the environment.

Open the virtualenv folder that we have just created

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

There are 5 folders available, the one that we are intersted is the Scipts folder, So open the “Scripts” folder

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Just open the command prompt from this folder, If you forgot how go back to Step 2 and open the prompt.

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

enter the command “activate” and hit enter.

Now you will notice that the prefix of your working directory has changed

How to activate virtual environment python windows. Смотреть фото How to activate virtual environment python windows. Смотреть картинку How to activate virtual environment python windows. Картинка про How to activate virtual environment python windows. Фото How to activate virtual environment python windows

Successfully we have completed the journey of creating a virtualenv and activating it, Every time you need to install a python package such as Tensorflow or OpenCV etc. Just make sure to activate the environment and then continue working.

Источники информации:

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

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