Your Python Coding Environment on Windows: Setup Guide

Your Python Coding Environment on Windows: Setup Guide

by Ian Currie basics tools

Are you interested in writing Python code on a Windows machine? Maybe you’re a lifelong Windows user getting into coding with Python, or perhaps you’re just beginning to branch out from macOS or Linux. In this tutorial, you’ll walk through an easy-to-follow and flexible Python coding setup on Windows 10.

To set up your Windows machine for Python coding, you’ll:

  • Clean and update a new Windows install
  • Use a package manager to bulk install key software
  • Use the built-in ssh-keygen to generate SSH keys and connect to your GitHub account
  • Set up a development environment, including PowerShell Core, pyenv for Windows, Python, and VS Code
  • Examine scripts and tools to automate the setup and installation process

Along the way, you’ll learn about various recommended tools for a complete, free, and mostly open-source Windows Python coding setup. You won’t get to know all the possible tools, but you’ll walk away with one setup that should be flexible enough for most situations.

If you’re a beginner to intermediate Pythonista, or you’re just looking to get set up on a Windows machine without having to think about all the different options out there, then this tutorial is for you.

Maybe you’re in a rush to get set up. If that’s the case, then you’ll find what you need in the section on fast-tracking your setup, where you’ll examine a PowerShell script to automate the process almost entirely. Jump over there if you need to get up and running quickly. That said, going over the first section will give you a good checklist to start with to make sure you won’t run into any errors.

Setting Up Your Basic Python Coding Environment in Windows

Say you’re sitting in front of a completely fresh Windows installation. In this section, you’ll go through the first steps that you should perform in that case. You’ll get an initial command line environment set up, install software via package managers, and configure essential Windows settings for a Python coding setup.

In addition to installing what you need, you’ll also learn how to get around some of Microsoft’s built-in programs that might get in the way. Your first step is to ensure that your Windows installation is up-to-date.

Updating Your Windows Installation

First, if your machine is new or you’ve disabled updates, then you’ll want to make sure your Windows installation is up-to-date. Updating is especially relevant if you want to use Windows Subsystem for Linux (WSL) and have Windows 10. It’s also a safeguard against the dreaded Windows auto-reboot.

Installing Windows updates can take an hour or two, but it’s relatively mindless. So if you’re starting here, line up some other tasks while waiting for the updates to complete.

To start the update process, go to the Start menu and search for Windows Update. Once there, prompt Windows to search for, download, and install any updates it can find:

Windows updates control paned

Once all the updates have been installed, you’ll probably be prompted to reboot the computer. Do this as many times as it asks you to.

You’ll probably have to repeat the update process two or three times. Once the first batch of updates have been installed and you’ve rebooted, if you go back to the update screen, then it’ll probably say that the system is up-to-date. However, if you wait a while and then check for updates again, it’ll likely find some more to install.

Once you have all the updates installed, then you’re ready to do the initial setup for the command line environment in your Windows Python coding setup.

Discovering the Windows Terminal

If you’ve always used Windows, then you may be used to using the Command Prompt and PowerShell through their own apps. Opening them this way may make you think that they’re self-contained programs. However, when you run these programs from the Start menu, two processes are running. One process is what performs the commands, and the other is a process to send your input and display the output.

The window that you see when you open the Command Prompt is the displaying process. The core of the Command Prompt is in the background awaiting your input that’s sent by the window. In this way, the window acts as a sort of host to the terminal.

For more information about the differences between command interpreters and interfaces, take a look at the introduction to the shell section in the article about the subprocess module.

Windows has created a new, open-source Windows Terminal to be a universal console host. It acts as an interface to multiple shells, allowing you to start the Command Prompt, PowerShell, and any other shell that you might have available as different tabs in the same host:

Windows Terminal Sample

Until the new Windows Terminal, many relied on other hosts, also called emulators, to manage their different shell sessions as tabs or as horizontal and vertical splits. One popular choice was ConEmu. ConEmu has more features than the Windows Terminal. However, Windows Terminal is catching up and has some features that ConEmu doesn’t, such as Unicode emoji support.

Windows Terminal also has the advantage of having the development effort of the open-source community and Microsoft behind it. Windows Terminal is improving and adding features surprisingly quickly. Crucially, for this tutorial, Windows Terminal is a lot easier to set up than ConEmu, so if you’re following along, move on to the next section to install Windows Terminal.

Installing Windows Terminal

For this tutorial’s setup, you should install the Terminal app from the Microsoft Store, accessible from the Start menu. Installing it from the Microsoft Store has a few advantages. One advantage is that it ensures that updates come automatically. Another advantage is that it’s painless to install. Other sources seem to break relatively often, presumably because Windows Terminal is being developed very quickly.

Windows Terminal is the only app that you’ll install without the package manager that you’ll get to later in the tutorial. That said, hopefully soon you’ll be able to manage all your software under one package manager.

Once you’ve installed Windows Terminal with the Microsoft Store, you should be able to find it in the Start menu under Terminal. If, for whatever reason, you can’t install it from the Microsoft Store, try the releases page in the GitHub repository.

When you start Windows Terminal, it should automatically start up with a new PowerShell tab:

Windows Terminal with Windows PowerShell tab

With that working correctly, you’ll be switching gears to perform some general Windows adjustments.

Configuring General Windows Settings

There are some general Windows settings that you’ll want to set to keep your sanity in check. This section contains some typical settings that Windows users will often immediately change when setting up Windows. Most of these settings are optional. Just make sure you do the first one listed, coming up next.

App Execution Aliases

App execution aliases are a special kind of alias for Windows. For example, if you type python on the command line, Windows will automatically ask you if you want to install the Microsoft Store version of Python.

App execution aliases are a feature to make things easier to get started, but they can interfere with other programs. For instance, when you install pyenv for Windows and install a few Python versions, the app execution aliases will interfere by not allowing you to access those Python versions.

You can search for the app execution alias control panel from the Start menu. The entry is called Manage app execution aliases. Here’s a screenshot of that control panel:

Windows Control panel for app execution aliases

You can usually turn all of these off, as you already have the Path environment variable to make sure apps are available on the command line. More on environment variables are coming later in the tutorial. The essential ones to disable are the Python-related ones.

The rest of the settings in this subsection are optional but are recommended for quality of life.

Windows Updates

It’s worth keeping Windows up-to-date, not only for security but for updates to all the developer tools like Windows Terminal and WSL. One Windows quirk that you’ll want to avoid is the auto-restart. For that, you can disable the option to restart your device with the Advanced Windows update options control panel:

Windows Settings to turn off auto reboot

Here, you’ll want to disable the option to restart your device as soon as possible after installing a new update. This setting is what typically causes the dreaded Windows auto-restart.

Disabling the auto-restart function is still not watertight, though. You’ll want to reboot Windows every few days, or every week at least, to be safe. If there’s one thing that UNIX systems seem to be far better at, it’s being able to go without a reboot for ages.

Windows Explorer

In an attempt to make Windows Explorer easier to use for non-developer types, it hides some information that you’ll probably want to see, so you should enable the following:

  • Show file extensions
  • Show hidden files
  • Show protected operating system files
  • Show the full path in the title bar

You can access these options from the file explorer, which you can open with Win+E, click on the File tab in the top left, and choose Change folder and search options. Under the View tab, you’ll be able to find these settings:

Windows 10 File Explorer Settings

With those settings adjusted, you’ll be able to see the previously hidden files and file extensions.

Managing Software in Windows

The default option for most Windows users when installing software is to go to a website, download an executable, and run it. The executable is typically a Windows Installer Package with an .msi file extension. Then you’ll be presented with a User Account Control (UAC) screen, asking you for permission to make changes to your device:

Windows 10 User Account Control screen

If that wasn’t enough, you then have to read a license agreement, click OK a bunch of times, and then close the installer. There must be a better way!

On UNIX-based systems, you get nice things called package managers, like Homebrew, apt, dnf and pacman. Why can’t Windows have those? Well, Windows does have a few package managers to choose from, the most popular of which is Chocolatey.

Windows package managers aren’t quite as advanced as their UNIX-based equivalents. However, they’re a massive step in the right direction for people who like to get stuff done.

Microsoft is developing its package manager, winget. While it’s good and getting better fast, it’s still not the most popular package manager for Windows and doesn’t have nearly as many packages to choose from as Chocolatey.

Before installing Chocolatey, there are a few things that you’ll need to do first.

Loosening Your Execution Policy

To install Chocolatey, you’ll want to first open up Windows Terminal, or your terminal program of choice, as an administrator.

Once you have an administrator terminal session open, you should be presented with a PowerShell tab.

To be able to install Chocolatey effortlessly, and for the automation script later in the tutorial, you’ll need to set your execution policy to something less strict than the default.

The execution policy sets how strict your system is about running scripts from other sources. For this tutorial, you’ll want to set it to RemoteSigned:

Windows PowerShell
PS> Set-ExecutionPolicy RemoteSigned
Execution Policy Change
The execution policy helps protect you from scripts that you don't trust.
...
Do you want to change the execution policy?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): y

You may not see the warning, because the execution policy might already be set. To double-check your setting, you can run Get-ExecutionPolicy. Once you have the correct execution policy, then you’re ready to download and run a script that’ll install Chocolatey.

Installing Chocolatey

To run the Chocolatey install script and to run the automated setup script that you’ll be looking at later in the tutorial, you can make a request to a hosted version of the script.

To run the hosted version of the installation script, you can run this command:

Windows PowerShell
PS> iwr -useb community.chocolatey.org/install.ps1 | iex

iwr is an alias for Invoke-WebRequest, and -useb means to use basic parsing, which downloads and parses the script from community.chocolatey.org/install.ps1. The result of this is the script text, which is then piped (|) into iex, which is an alias for Invoke-Expression, which runs the script. The script installs Chocolatey.

Once the installation is done, you should be able to call choco from the same prompt. However, the command is not always available from the same prompt after installation. In that case, you can restart the terminal, ensuring it’s still in administrator mode for what’s coming up in the tutorial. If that also fails, reboot your system to refresh the environment.

Using Chocolatey

With Chocolatey installed, you’re ready to manage almost all your software with simple commands. Remember that to install, upgrade, and uninstall software, you’ll need to start the Terminal session as an administrator.

Try starting an elevated Terminal session, and then install a package of your choice from the online package search. The install command is demonstrated below with 7zip, an open-source file archiver:

Windows PowerShell
PS> choco install 7zip
7zip.install v22.0 [Approved]
7zip.install package files install completed. Performing other installation steps.
The package 7zip.install wants to run 'chocolateyInstall.ps1'.
Note: If you don't run this script, the installation will fail.
Note: To confirm automatically next time, use '-y' or consider:
choco feature enable -n allowGlobalConfirmation
Do you want to run the script?([Y]es/[A]ll - yes to all/[N]o/[P]rint):

At the confirmation prompt, type Y and press enter. Chocolatey will then install the package. If you want to disable the behavior of double-checking if you want to install a package, then you can send this command:

Windows PowerShell
PS> choco feature enable -n allowGlobalConfirmation

Now the installation process won’t prompt you with the annoying Are you sure? type of prompts. That said, you can also pass in this option for each install command by adding the -y flag.

If you want to search available packages from the command line, then you can do that with the choco search [keyword] command. To see a list of your installed packages, you can use the choco list command with the --local-only flag. Finally, to upgrade and uninstall, there are choco upgrade and choco uninstall commands for that too:

Windows PowerShell
PS> choco upgrade [package-name]
PS> choco upgrade all # keyword to try upgrade all packages
PS> choco uninstall [package-name]

Note that upgrading all packages might take a while.

You’re now ready to start using Chocolatey by installing a small set of software to help you clean up and uninstall any bloatware that may have come preinstalled on your system.

Debloating Your Machine and Uninstallating Software

Once you have your package manager, one of the first things you may want to do with a fresh install is to clean it up. This section is optional and may not even be necessary for your system.

If you’ve installed Windows from a Microsoft image, then there’s probably not much to remove. If your PC came preinstalled, then it’s potentially filled with a bunch of bloatware.

For instance, manufacturers often include third-party antivirus software but may not deactivate Windows Defender. Having more than one antivirus software can cause strange problems and significantly impact your PC’s performance. Besides, Windows Defender or Microsoft Defender is safe, so if you don’t need the additional antivirus for any particular reason, you can rest assured that the built-in antivirus is adequate to keep you safe.

To start off with an immaculate install on a preinstalled system, some would even go as far as to reset the Windows installation completely. This option is available via the Start menu by searching for reset. However, this nuclear option can turn out to be a hassle because your machine may require special drivers that the Windows install process doesn’t have access to.

It’s also inevitable that at some point, you’ll install something that didn’t turn out to be what you wanted. Perhaps it was a package that wasn’t available on Chocolatey, or you just forgot to use Chocolatey. Or, to your horror, you clicked a suspect link and installed some persistent spyware.

To clean up and remove programs, you might want a decent uninstaller, ideally one that’ll let you uninstall in bulk and will also do the extra work of cleaning up files and folders that sometimes get left behind.

Spyware, malware, and adware that slip through the cracks are especially good at leaving behind services that reinstall themselves once you’ve supposedly uninstalled them.

Bulk Crap Uninstaller or BCU, is a fantastic open-source uninstaller that’ll seek out all sorts of programs and purge them:

Windows PowerShell
PS> choco install bulk-crap-uninstaller

Once it’s installed and open, it’ll allow you to select multiple programs and automate the uninstallation and cleanup process as much as possible:

A screenshot of Bulk Crap Uninstaller

BCU will detect which uninstallation processes can’t be automated and uninstall those first. Then it’ll let you know that all the rest of the programs can be uninstalled without your intervention.

After the main uninstall process, BCU will perform a deep clean, showing you leftover files, services, and registry entries that you may want to delete.

Other free options are available, such as Geek Uninstaller, which is generally faster if all you’re looking to do is uninstall one or two programs.

Some programs are very difficult to uninstall because they’re deeply embedded into Windows. If you want to minimize their presence, then you may also want to play around with Winaero Tweaker:

Windows PowerShell
PS> choco install winaero-tweaker

Winaero Tweaker is a utility that’ll allow you to change a bunch of settings that are either not accessible with the Settings app or are very difficult to change. For example, it can disable Cortana and OneDrive if you don’t intend to use them.

Once you’re done with general cleaning, it’s time to dig in further and explore the Windows command line experience.

The classic Windows command line experience is associated with the command prompt, also known as cmd.exe:

The cmd.exe Windows Command Prompt

But times have moved on, and these days you’ll want to use PowerShell Core, a cross-platform, object-oriented shell that can do much more than the Command Prompt.

PowerShell was designed by Microsoft, with Bruce Payette at the helm, to be a powerful and relatively easy-to-understand tool to help with all aspects of managing a Windows machine. It’s a shell, a scripting environment, and an automation tool. It can be used for everything from personal scripts up to DevOps.

PowerShell does get a bit of a bad reputation for being strange and verbose, but it’s a compelling system that can get a lot done. It just takes a little getting used to.

On Windows 10, Windows PowerShell comes installed by default. However, the newer PowerShell Core doesn’t. Windows PowerShell became PowerShell Core starting with version 6, and that’s when it became a cross-platform shell and open source to boot.

Since PowerShell Core doesn’t come with Windows 10 by default, you’ll want to install it.

Installing PowerShell Core

Now you’re ready to install the latest version of PowerShell Core with Chocolatey:

Windows PowerShell
PS> choco install powershell-core

Once that’s done, you should now be able to call pwsh to start a PowerShell Core session. If that doesn’t work, try the command refreshenv, and if that fails, restart the terminal session:

Windows Terminal Application with PowerShell Core tab

Note that when you upgrade PowerShell Core, you’ll want to update from another shell, such as the old Windows PowerShell, which will still be available, or the Command Prompt. Trying to replace an in-use PowerShell Core can be problematic. So when you upgrade it, ensure that all PowerShell Core instances are closed.

Now that you have the latest version of PowerShell Core installed, you’ll be able to use it to do all your typical shell-based tasks.

Getting to Grips With PowerShell Basics

PowerShell Core has a lot of functionality, but you don’t need all of it; heck, you don’t even need a fraction of it. Below are some of the most common commands for navigating and managing your file system:

Alias Full PowerShell Command Explanation Bash Equivalent
ls Get-ChildItem List the contents of the current working directory ls
cd Set-Location Change your current working directory cd
rm Remove-Item Delete an item rm
rm -recurse -fo Remove-Item -Recurse -Force Delete a folder recursively rm -rf
mkdir New-Item -ItemType Directory Create a new directory mkdir
ni New-Item -ItemType File Create a new file touch
cat Get-Content Print the contents of a file to the screen cat

You’ll see that it’s not so different from a typical POSIX shell, like what you find on UNIX-based systems like Linux or macOS.

If you’re confused by PowerShell, the confusion often stems from the fact that PowerShell, like Python, is very object-oriented, while most shells are purely text-based. Once you start getting your head around the change, it makes a lot more sense.

If you’re interested in learning more about PowerShell, Bruce Payette himself wrote Windows PowerShell in Action. Even though the book uses Windows PowerShell, it’s great for a general introduction.

Now that you’re whizzing around the command line, there are things that you might want to alias yourself to customize your experience and make it better for your workflows.

Customizing Your PowerShell Experience

One task that you’ll want to do at some point is to configure your PowerShell profile. The profile isn’t necessary, but it’s a great tool to take advantage of. Your profile is a PowerShell script that you use to configure your command line environment—it’s the PowerShell equivalent of a Bash .bashrc file.

Whenever you start a new PowerShell session, the profile script will run. If you have more than one machine, then it’s a great document to back up and share across all of them. The profile is also great for initializing a new machine. That way, you get all your shortcuts and custom functions from the get-go.

First off, you’ll need to create the profile because it’s not created by default when PowerShell Core is installed:

Windows PowerShell
PS> ni -Force $PROFILE

This command uses the ni command, an alias for New-Item. It uses the $PROFILE PowerShell variable, which points to the path where PowerShell will look for a profile. The -Force flag is used because PowerShell may need to create some directories along the way.

Once you’ve created the profile, you can open it with Windows Notepad:

Windows PowerShell
PS> notepad $PROFILE

Once it’s open, add any PowerShell commands that you want to it. For example, you can set aliases for programs you use often:

PowerShell Script
# Microsoft.PowerShell_profile.ps1

Set-Alias n notepad

In this case, n will become aliased to the command notepad. So if you want to open up notepad, now you can just type n. Note that any changes you make to the profile will only be apparent in the next session that you start up.

You can also add functions to your profile:

PowerShell Script
# Microsoft.PowerShell_profile.ps1

function grep {
  $input | out-string -stream | select-string $args
}

If you come from a UNIX background, grep may be a welcome utility to find on Windows! It’s a way to filter many lines of output. For instance, if you’re listing a large directory and want to show only lines that contain a specific string, then you can use this utility like this:

Windows PowerShell
PS> ls large-directory | grep python

This command lists the contents of a large directory and only shows lines that contain the string python.

PowerShell also has a module system to extend and customize your command line experience, and in the next section, you’ll get a few recommendations for handy modules to install.

Discovering PowerShell Modules

PowerShell has a rich ecosystem of optional modules that you can install to enhance your command line experience further. Here’s a list of a few very useful, but entirely optional, ones:

  • ZLocation: This module helps you navigate extremely quickly to commonly accessed folders.
  • Oh My Posh: This module makes it easy to customize your PowerShell prompt to look great and add a bunch of extra functionality too.
  • PSFzf: This module wraps the power of the search utility fzf inside PowerShell. You need to install fzf first, which can be done with choco install fzf.
  • posh-git: This module allows further customization of your prompt, but will crucially bring tab completion to your Git commands.

You can install these modules with the Install-Module command, though each of the links will have more information about how to install it and set it up properly.

You’ve set up some customizations for your PowerShell sessions, but there are some things that need to be configured at a deeper level. In the next section, you’ll be covering environment variables.

Configuring Environment Variables

Environment variables are general-purpose key-value pairs that are available at many levels of the operating system. They typically contain information about how to run programs, or where to find resources. Python, for instance, runs differently if certain environment variables are set or not.

While you shouldn’t need to do much in terms of your own configuration as part of getting your machine set up, it’s always something that comes up sooner or later when troubleshooting. So it’s worth knowing your way around this topic.

Discovering Environment Variables With PowerShell

PowerShell has access to environment variables and a lot of related functionality. If you’re interested in digging deeper, Microsoft has a page dedicated to these variables in the PowerShell documentation.

To see all the environment variables available to your current PowerShell session, you can navigate to a pseudo drive called ENV, just as if it were a drive like C or D:

Windows PowerShell
PS> cd ENV:
PS> pwd # alias for Get-Location

Path
----
Env:\

PS> ls

Name                           Value
----                           -----
ALLUSERSPROFILE                C:\ProgramData
ANSICON                        166x32766 (166x66)
ANSICON_DEF                    7
APPDATA                        C:\Users\RealPython\AppData\Roaming
AZ_ENABLED                     False
ChocolateyInstall              C:\ProgramData\chocolatey
...

Once you’ve navigated to the ENV: pseudo drive, you can call ls to list all the environment variables available to your current PowerShell session.

There’s also a Graphical User Interface (GUI) control panel for environment variables, which you’ll come to later in this section.

Environment variables are different from variables like $PROFILE because the environment variables are typically available to all programs in your user space, while $PROFILE is a PowerShell-only variable.

The Env:Path variable is particularly prone to easy mistakes and can be frustrating if you don’t understand what’s happening.

Understanding the Path Environment Variable

One of the environment variables you should become familiar with is the Path environment variable. Path is a variable that contains a list of paths to directories that contain executables. Path is kept by your system as a way to have programs always close at hand.

You can see the Path environment variable in action whenever you call choco or python from the command line, for instance. You know that the target executable may not be in the current working directory, but Windows can still start it.

For instance, Chocolatey adds a directory to Path where it puts executables that you might want to call from the command line. The directory it adds to the Path environment variable is C:\ProgramData\chocolatey\bin, and in that directory you’ll at least find choco.exe. With this set, when you call choco from the command line, Windows will search each path in the Path environment variable for a folder that contains a choco executable.

To see what paths are in your Path variable, from PowerShell you can call the following command:

Windows PowerShell
PS> (cat ENV:Path) -Split ";"

cat is an alias for Get-Content, which returns a string object of the contents of the Path variable. You can wrap that object in brackets to call the -Split operator to see each path on a separate line.

The list visible after running the previous command is the list of locations that your system will look for when evaluating which program to run. Once you have Python installed, the location of the Python executable will need to be added so that you can call python from anywhere.

With some knowledge of environment variables and the Path variable, you’re now ready to learn how to make changes to them if necessary.

Setting and Changing Environment Variables

There are various ways to change environment variables—the most common being with the GUI control panel.

Open the Start menu and search for Edit the system environment variables, which opens up a System Properties window. In the Advanced tab, click on the button Environment Variables. There you’ll see User and System variables, which you’ll be able to edit:

If you’re the only user of your computer, then you can just set the user variables. If you want the variable to be accessible by all users on the machine, set the system variables.

You can also set environment variables from an elevated PowerShell prompt by using .NET API methods, like this:

Windows PowerShell
PS> [Environment]::SetEnvironmentVariable("TEST", "VALUE", "User")

This command sets an environment variable with the key "TEST", whose value is "VALUE", and whose scope is "User". The scope can be "User", "Process" or "Machine". You can use "Machine" if you want the environment variable to be available to all users, while "User" is for just the current user. The "Process" scope will only set a variable for the current PowerShell session and the session’s child processes.

You can create temporary environment variables with pure PowerShell by using the following command:

Windows PowerShell
PS> $ENV:TEST = "VALUE"

But a program outside the context of your PowerShell session won’t have access to that variable. What’s more, if you don’t add this statement to your profile too, then it won’t be available in your next PowerShell session.

If you need to change the Path variable, there are a few more things to bear in mind.

Changing the Path Environment Variable

Because the Path environment variable is a list of many paths, you need to be careful when modifying it, so that you don’t overwrite the whole Path with just one path.

Typically, if you’re going to be doing that from PowerShell as a temporary environment variable, then you’ll need to append the new value with string concatenation:

Windows PowerShell
PS> $env:Path = "$env:Path;C:\new\path"

Perhaps the easiest way to change the Path environment variable is with the GUI control panel, which keeps each Path entry on its own line, so it’s easier to avoid making a mistake.

You’ll often need to restart the shell session for any changes to environment variables to take effect. Chocolatey comes with a utility script that allows you to refresh the environment:

Windows PowerShell
PS> refreshenv

Note that this won’t work if you installed Chocolatey in the same session. That said, sometimes even with that script, it’s going to be necessary to reboot.

Now that you know how to do some Path troubleshooting and are relatively comfortable with your new command-line setup, it’s time to install Python with pyenv for Windows.

Setting Up Core Python Coding Software in Windows

Now it’s time to get set up with a few different Python versions. Even though it’s a good idea to keep up-to-date with the latest version of Python, it’s not uncommon to run into projects that won’t work with the latest and greatest. There are even programs that still run Python 2, after all! So it’s best to be ready to install any number of versions of Python, and to be able to switch between them easily.

Installing Python With pyenv for Windows

pyenv for Windows is a port of the original pyenv which only runs on UNIX-based systems. The Windows version isn’t quite as fully featured as the UNIX version, but it’s still fully functional.

With Chocolatey, installing pyenv for Windows is just like installing any other package:

Windows PowerShell
PS> choco install pyenv-win

Once pyenv for Windows is installed, you’ll want to update the local index of Python versions available for install, which takes a few minutes. After the update is done, you’ll want to install a couple of versions of Python:

Windows PowerShell
PS> pyenv update
:: [Info] :: Mirror: https://www.python.org/ftp/python
:: [Info] :: Scanned 172 pages and found 563 installers.
PS> pyenv install --quiet 3.10.5 3.9.12
:: [Info] :: Mirror: https://www.python.org/ftp/python
:: [Downloading] :: 3.10.5 ...
...
:: [Installing] :: 3.10.5 ...
:: [Downloading] :: 3.9.12 ...
...
:: [Installing] :: 3.9.12 ...

The install command will install two Python versions without your manual intervention because of the --quiet flag.

You can use the pyenv global command to switch between Python versions and then check the version of Python that’s active with the -V for version flag:

Windows PowerShell
PS> pyenv global 3.10.5
PS> python -V
Python 3.10.5
PS> pyenv global 3.9.12
PS> python -V
Python 3.9.12

As you can see, switching between different Python versions is only a matter of one command.

If you have a project requiring a specific version of Python, you have a few options for handling that. You can use the pyenv local command, which will create a file in the current working directory to ensure you’re always running that version of Python while in that directory.

Or you can create a virtual environment with that version active:

Windows PowerShell
PS> pyenv global 3.9.12
PS> python -V
Python 3.9.12
PS> python -m venv venv

PS> pyenv global 3.10.5
PS> python -V
Python 3.10.5

PS> ./venv/Scripts/activate
(venv) PS> python -V
Python 3.9.12

If you create a Python virtual environment with a particular version of Python active, then that virtual environment will keep pointing to that version of Python.

For more in-depth information about pyenv, check out the dedicated tutorial on it. Just note that since that tutorial is for the UNIX version, some functionality may not work as it does on Windows. In those cases, check out the pyenv for Windows repository.

Now that you have Python, you’ll want a way to collaborate with other programmers.

Installing Git on Windows

Git is the most popular and widely supported version control system among programmers. If you’ve never used a version control system before, it manages changes to your project, allowing you to roll back to any state your code has been in from the moment you started using version control.

Git works with repositories. A repository is basically a folder with a tracked history. GitHub is a website that allows you to host your repositories. Once a repository is hosted, many people can work on the project simultaneously and from anywhere. You can work offline and then sync back up to the main repository once you connect to the Internet.

Git is easy to install with Chocolatey:

Windows PowerShell
PS> choco install git

That’s it! You should now be able to call git from the PowerShell prompt. If this doesn’t work and you get a message saying that this command can’t be recognized, try refreshenv. If that fails, then you can resort to restarting the PowerShell session or just rebooting the machine.

Git, like PowerShell, also searches for a config file in the user’s home folder. You can create this manually in the root home path, or by using some built-in Git commands:

Windows PowerShell
PS> git config --global user.name "John Doe"
PS> git config --global user.email john.doe@domain.com

That said, if you try to make a commit, Git will prompt you to add this information, which will create the .gitconfig file.

With Git up and running, you’ll want to be able to connect with GitHub from the command line, but for that, you’ll need to set up your SSH key.

Using SSH to Connect to GitHub

The way to connect to GitHub is with SSH, or Secure Shell. For this, you’ll need to create some SSH keys. The process that you’ll follow in this section will generate two keys, a private and a public one. You’ll be uploading the public one to your GitHub account.

Open up a PowerShell session and make sure that you have Open-SSH, which should’ve been installed by default:

Windows PowerShell
PS> ssh
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
           [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
           [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]
           [-i identity_file] [-J [user@]host[:port]] [-L address]
           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
           [-Q query_option] [-R address] [-S ctl_path] [-W host:port]
           [-w local_tun[:remote_tun]] destination [command]

If you don’t see a similar output, follow the instructions on the Windows documentation to install Open-SSH. You can also install it from a Chocolatey package.

You’ll first create your keys with ssh-keygen, pressing enter at each prompt to use the default option:

Windows PowerShell
PS> ssh-keygen -C john.doe@domain.com
Generating public/private rsa key pair.
Enter file in which to save the key (C:\Users\Real Python/.ssh.id_rsa):
Created directory 'c:\Users|Real Python/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\Real Python/.ssh/id_rsa.
Your public key has been saved in C:\Users\Real Python/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa jondoe@domain.com
The key's randomart image is:
+---[RSA 3072]----+
| E+===+*++.o.    |
|..=+=o+O+ o.o    |
|o+o++.B.o oo     |
|o+o*oo o o .     |
| o+o.   S .      |
|  o              |
|                 |
|                 |
|                 |
+----[SHA256]-----+

You can add a passphrase if you want extra protection, but it’s convenient not to have to input your password every time you push your work to GitHub. With your keys generated, output the contents of the public key so that you can select and copy it to your clipboard:

Windows PowerShell
PS> cat ~/.ssh/id_rsa.pub

The output of this last cat command is what you’ll need to copy into your GitHub account.

To copy the key to your GitHub account, you first must make sure that you’ve signed up for an account. Once you’ve signed up and logged in, if you go to your GitHub settings, you should find the option to manage your SSH and GPG keys. Once in there, you should be able to see where to paste your SSH key.

After that, you can test the connection:

Windows PowerShell
PS> ssh -T git@github.com
Hi John Doe! You've successfully authenticated, but GitHub doesn't provide shell access.

If you get this successful authentication message, then you’re ready to work with GitHub from the command line.

Now that you have Git up and running, it’s time to set up your code editor.

Setting Up VS Code

VS Code is an amazingly extensible free, mostly open-source, general-purpose editor. It’s also the most popular. It can be used for many languages, but in this section, you’ll get it set up for Python.

You can install VS Code with Chocolatey:

Windows PowerShell
PS> choco install vscode

Remember to run the install command from an elevated PowerShell prompt.

VS Code has a rich extension ecosystem to aid your productivity. The official Microsoft Python extension often comes installed by default, but if not, you should make sure to install it.

To install an extension, you click the extensions icon in the activity bar:

The Extensions button in VS Code

Then use the search box to search for the Python extension linked above.

The Python extension will provide you with IntelliSense for Python, which is a way for your editor to give you suggestions for autocomplete and will provide you a wealth of information in detailed tooltips.

Another extension, if you plan on using WSL, is the WSL connector, which will allow you to edit files as if you were running on Linux.

It’s also worth setting up Settings Sync, since that’ll link your VS Code settings and your extension list to your GitHub or Microsoft account, taking care of backup and making it fast to get set up on a new machine.

With VS Code set up, you’re ready to test your setup to ensure that it’s working.

Testing Out Your Setup

Congratulations, you’re pretty much good to go. In this section, you’ll quickly test your setup to ensure everything is working correctly.

In the following snippet, you’ll test out creating a folder, creating a virtual environment, installing a package, initializing a Git repository, and making sure that VS Code integrates with that setup:

Windows PowerShell
PS> mkdir test

    Directory: C:\Users\RealPython

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----            27/06/22    18:19                test

PS> cd test
PS> pyenv versions
* 3.10.5 (set by C:\Users\RealPython\.pyenv\pyenv-win\version)
  3.9.12

PS> python -m venv venv
PS> .\venv\Scripts\activate
(venv) PS> python -m pip install requests
Collecting requests
...
Successfully installed certifi charset-normalizer idna requests urllib3

(venv) PS> git init
Initialized empty Git repository in C:/Users/RealPython/test/.git/

(venv) PS> ni test.py

    Directory: C:\Users\RealPython\test

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---            27/06/22    18:25              0 test.py

(venv) PS> code .

With VS Code now open, at the bottom right, you should be able to see which Python environment you’re in:

If it’s not showing venv and IntelliSense isn’t working, then you can invoke the command palette with Ctrl+Shift+P and search for the Python: Select Interpreter command. Choose the option that points to the path of your virtual environment. With the virtual environment selected, VS Code should display at the bottom of your VS Code Window as 3.10.5 (‘venv’:venv).

You should also be able to see VS Code’s Git integration working. If you change a file or add a new one, then you’ll see indications of that change in the editor window and the file explorer.

Well done! You now have a powerful and flexible setup on Windows. While using a package manager is far more efficient than manually downloading and executing installers, maybe you’re looking for an even faster way.

Fast-Tracking Your Windows Python Coding Setup

Maybe this is all a bit slow for you, or perhaps you just want to get started with automating the process. There are tools to automate installation at an industrial scale, like Boxstarter and Ansible, but this section is aimed more toward tinkerers who want to see what kind of things you can do yourself.

In this section, you’ll fast-track your minimal setup, skipping any extra steps, and get developing as soon as humanly possible.

Configuration Repository

When first trying to automate a new installation, you typically run into the issue of getting your scripts onto the new machine to run them. A file syncing service can work, but those often take a long time to do their initial sync.

A great solution to this problem is having a repository containing configuration files and scripts. Sometimes other snippets may be included there, too—sort of a coder’s personal cookbook.

Here, you can keep your PowerShell profile, your Git config files, other config files, and any scripts or notes that you might want. Once you have files hosted on GitHub, then you can get raw links to them and use PowerShell to download them:

The "Raw" button on a GitHub file

To get a raw link, navigate to the file that you want to use in GitHub, and when you’re looking at the contents of the file, you should be able to see a button that says Raw. This button will take you to a URL that looks something like this:

HTTP
https://raw.githubusercontent.com/[USER]/[REPO]/[COMMIT_SHA_OR_BRANCH]/path/to/file

Now you can use this URL to fetch the content and run it from your new machine. You can also host individual files with a GitHub Gist.

To take things a step further, to avoid having to type out the whole link, you can pass it through a URL shortener such as bitly, which will shorten the link:

HTTP
https://bit.ly/xxxxxxx

Now it’s time to do the main bulk of setup. Armed with this short link, all you have to do is disable the Python-related app execution aliases, start an elevated PowerShell session, and run the following:

Windows PowerShell
PS> Set-ExecutionPolicy RemoteSigned -Force
PS> iwr -useb bit.ly/xxxxxxx | iex

Then everything will be taken care of for you, and you can run an errand while the installation process ticks along. Now that you’ve chosen your platform for hosting your setup script, you’ll need the actual script!

Running a Setup Script

In this section, you’ll examine a sample installation script that’ll install some minimal dependencies that you’ll probably need to code with Python, especially if you want to contribute to open-source projects on GitHub.

The prerequisites for running this script are:

  1. Setting your execution policy to RemoteSigned
  2. Disabling Python-related app execution aliases

With those two tasks done, you’re just about ready to expand the collapsible box below and run the script:

PowerShell Script
# setup.ps1

Write-Output "Downloading and installing Chocolatey"
Invoke-WebRequest -useb community.chocolatey.org/install.ps1 | Invoke-Expression

Write-Output "Configuring Chocolatey"
choco feature enable -n allowGlobalConfirmation

Write-Output "Installing Chocolatey Packages"
choco install powershell-core
choco install vscode
choco install git --package-parameters="/NoAutoCrlf /NoShellIntegration"
choco install pyenv-win

# The Google Chrome package often gets out of sync because it updates so
# frequently. Ignoring checksums is a way to force install it.
choco install googlechrome --ignore-checksums
# Google Chrome auto-updates so you can pin it to prevent Chocolatey from
# trying to upgrade it and inadvertently downgrading it.
# You could also add VS Code here if you like.
choco pin add -n googlechrome

refreshenv

# The refreshenv command usually doesn't work on first install.
# This is a way to make sure that the Path gets updated for the following
# operations that require Path to be refreshed.
# Source: https://stackoverflow.com/a/22670892/10445017
foreach ($level in "Machine", "User") {
    [Environment]::GetEnvironmentVariables($level).GetEnumerator() |
    ForEach-Object {
        if ($_.Name -match 'Path$') {
            $combined_path = (Get-Content "Env:$($_.Name)") + ";$($_.Value)"
            $_.Value = (
                ($combined_path -split ';' | Select-Object -unique) -join ';'
            )
        }
        $_
    } | Set-Content -Path { "Env:$($_.Name)" }
}

Write-Output "Setting up pyenv and installing Python"
pyenv update
pyenv install --quiet 3.10.5 3.9.12
pyenv global 3.10.5

Write-Output "Generating SSH key"
ssh-keygen -C john.doe@domain.com -P '""' -f "$HOME/.ssh/id_rsa"
cat $HOME/.ssh/id_rsa.pub | clip

Write-Output "Your SSH key has been copied to the clipboard"

This script will try and install Chocolatey, install key software mentioned in this tutorial, install a couple of Python versions with pyenv, generate your SSH key and present it to you so that you can go to GitHub and add it to your account.

If you’re going to use it, be sure to customize the software you want to install and to swap in your email on the ssh-keygen line.

Make sure the Python app execution aliases are disabled, get the shortened link to the raw contents of the file hosted on GitHub as described in the previous section, and run the following command in an elevated PowerShell session:

Windows PowerShell
PS> Set-ExecutionPolicy RemoteSigned -Force
PS> iwr -useb bit.ly/xxxxxxx | iex

With that, you should be ready and raring to go! The only optional steps left are to configure general Windows settings, maybe debloating and setting up your config files along the way.

Conclusion

Now you’ve set up your Windows machine to do some development with Python. You’ve explored some modern tools to manage your software and different Python versions. Not only that, you got a crash course in PowerShell and saw how you might start to automate an installation.

In this tutorial, you’ve successfully:

  • Cleaned and updated a new Windows install
  • Used Chocolatey to bulk install key software
  • Used the built-in ssh-keygen to generate SSH keys and connect to your GitHub account
  • Set up a development environment, including PowerShell Core, pyenv for Windows, Python, and VS Code
  • Written a script to automate the process as much as possible.

With this Windows setup, you’re ready to start coding with Python. Since you’re also connected to GitHub, you’re ready to try your hand at contributing to open-source projects, too. In the comments, feel free to share what you’ve been working on!

Other Nifty Windows Software

Now that you have Windows all set up for Python coding, you may want to make your life even easier. Here are some great Windows utilities that can help you do just that:

  • Everything: A great search utility that leverages Windows-only file indexing tools. It can be used as a general file finder and an application launcher. It’s fast!
  • Windows Subsystem for Linux: If you want to have an almost fully fledged Linux experience within Windows, check out WSL. This isn’t a Chocolatey package.
  • Autohotkey: An easy-to-use and hugely popular automation tool only for Windows. Some people stick with Windows just for AHK!

With these utilities installed, you’re ready to tackle any coding challenge.

🐍 Python Tricks 💌

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.

Python Tricks Dictionary Merge

About Ian Currie

Ian Currie Ian Currie

Ian is a Python nerd who relies on it for work and much enjoyment.

» More about Ian

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:

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

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

Level Up Your Python Skills »

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

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

Level Up Your Python Skills »

What Do You Think?

Rate this article:

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!

Keep Learning

Related Tutorial Categories: basics tools