4. Using Python on Windows¶

This document aims to give an overview of Windows-specific behaviour you should know near when using Python on Microsoft Windows.

Unlike almost Unix systems and services, Windows does not include a system supported installation of Python. To brand Python available, the CPython squad has compiled Windows installers (MSI packages) with every release for many years. These installers are primarily intended to add a per-user installation of Python, with the core interpreter and library beingness used by a single user. The installer is also able to install for all users of a single machine, and a separate Nada file is bachelor for application-local distributions.

As specified in PEP 11, a Python release only supports a Windows platform while Microsoft considers the platform under extended support. This ways that Python 3.10 supports Windows 8.1 and newer. If you require Windows 7 support, delight install Python 3.8.

There are a number of different installers available for Windows, each with certain benefits and downsides.

The full installer contains all components and is the all-time pick for developers using Python for any kind of project.

The Microsoft Store parcel is a simple installation of Python that is suitable for running scripts and packages, and using IDLE or other evolution environments. It requires Windows 10, but tin can exist safely installed without corrupting other programs. It too provides many convenient commands for launching Python and its tools.

The nuget.org packages are lightweight installations intended for continuous integration systems. It tin can be used to build Python packages or run scripts, but is not updateable and has no user interface tools.

The embeddable package is a minimal package of Python suitable for embedding into a larger application.

4.1. The full installer¶

4.i.1. Installation steps¶

Iv Python 3.10 installers are available for download - two each for the 32-bit and 64-bit versions of the interpreter. The spider web installer is a small initial download, and it will automatically download the required components as necessary. The offline installer includes the components necessary for a default installation and but requires an cyberspace connectedness for optional features. See Installing Without Downloading for other ways to avert downloading during installation.

After starting the installer, one of two options may exist selected:

../_images/win_installer.png

If you select "Install Now":

  • Y'all will not need to exist an administrator (unless a system update for the C Runtime Library is required or y'all install the Python Launcher for Windows for all users)

  • Python will be installed into your user directory

  • The Python Launcher for Windows will exist installed according to the selection at the bottom of the first folio

  • The standard library, test suite, launcher and pip will be installed

  • If selected, the install directory volition be added to your PATH

  • Shortcuts volition merely be visible for the electric current user

Selecting "Customize installation" will let you lot to select the features to install, the installation location and other options or post-install deportment. To install debugging symbols or binaries, y'all volition demand to use this option.

To perform an all-users installation, you should select "Customize installation". In this case:

  • You may exist required to provide administrative credentials or approval

  • Python will be installed into the Program Files directory

  • The Python Launcher for Windows volition be installed into the Windows directory

  • Optional features may be selected during installation

  • The standard library can be pre-compiled to bytecode

  • If selected, the install directory will be added to the organisation PATH

  • Shortcuts are available for all users

4.i.two. Removing the MAX_PATH Limitation¶

Windows historically has limited path lengths to 260 characters. This meant that paths longer than this would not resolve and errors would issue.

In the latest versions of Windows, this limitation can be expanded to approximately 32,000 characters. Your ambassador volition need to actuate the "Enable Win32 long paths" group policy, or set up LongPathsEnabled to 1 in the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem .

This allows the open() part, the os module and nearly other path functionality to accept and return paths longer than 260 characters.

Afterwards irresolute the above option, no farther configuration is required.

Inverse in version 3.vi: Support for long paths was enabled in Python.

4.1.3. Installing Without UI¶

All of the options available in the installer UI tin can also be specified from the command line, allowing scripted installers to replicate an installation on many machines without user interaction. These options may also be set without suppressing the UI in order to change some of the defaults.

To completely hide the installer UI and install Python silently, laissez passer the /quiet option. To skip past the user interaction only still display progress and errors, pass the /passive option. The /uninstall option may be passed to immediately begin removing Python - no confirmation prompt will be displayed.

All other options are passed as name=value , where the value is usually 0 to disable a feature, 1 to enable a feature, or a path. The full list of bachelor options is shown below.

Name

Description

Default

InstallAllUsers

Perform a organization-wide installation.

0

TargetDir

The installation directory

Selected based on InstallAllUsers

DefaultAllUsersTargetDir

The default installation directory for all-user installs

%ProgramFiles%\Python X.Y or %ProgramFiles(x86)%\Python 10.Y

DefaultJustForMeTargetDir

The default install directory for simply-for-me installs

%LocalAppData%\Programs\PythonXY or %LocalAppData%\Programs\PythonXY-32 or %LocalAppData%\Programs\PythonXY-64

DefaultCustomTargetDir

The default custom install directory displayed in the UI

(empty)

AssociateFiles

Create file associations if the launcher is also installed.

i

CompileAll

Compile all .py files to .pyc .

0

PrependPath

Add install and Scripts directories to PATH and .PY to PATHEXT

0

Shortcuts

Create shortcuts for the interpreter, documentation and IDLE if installed.

1

Include_doc

Install Python transmission

i

Include_debug

Install debug binaries

0

Include_dev

Install developer headers and libraries

1

Include_exe

Install python.exe and related files

1

Include_launcher

Install Python Launcher for Windows.

ane

InstallLauncherAllUsers

Installs Python Launcher for Windows for all users.

1

Include_lib

Install standard library and extension modules

i

Include_pip

Install arranged pip and setuptools

ane

Include_symbols

Install debugging symbols (*.pdb)

0

Include_tcltk

Install Tcl/Tk support and IDLE

1

Include_test

Install standard library test suite

one

Include_tools

Install utility scripts

one

LauncherOnly

Simply installs the launcher. This will override almost other options.

0

SimpleInstall

Disable nearly install UI

0

SimpleInstallDescription

A custom message to display when the simplified install UI is used.

(empty)

For instance, to silently install a default, system-wide Python installation, you could use the following control (from an elevated command prompt):

                python-3.nine.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0              

To allow users to easily install a personal re-create of Python without the examination suite, y'all could provide a shortcut with the following command. This will display a simplified initial folio and disallow customization:

                python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0     SimpleInstall=1 SimpleInstallDescription="Just for me, no examination suite."              

(Note that omitting the launcher also omits file associations, and is only recommended for per-user installs when there is besides a system-wide installation that included the launcher.)

The options listed higher up can likewise be provided in a file named unattend.xml alongside the executable. This file specifies a list of options and values. When a value is provided equally an attribute, it will be converted to a number if possible. Values provided as element text are always left as strings. This example file sets the same options as the previous example:

                                <Options>                <Option                Name=                "InstallAllUsers"                Value=                "no"                />                <Option                Name=                "Include_launcher"                Value=                "0"                />                <Option                Proper noun=                "Include_test"                Value=                "no"                />                <Pick                Name=                "SimpleInstall"                Value=                "yes"                />                <Option                Name=                "SimpleInstallDescription"                >Simply for me, no exam suite</Option>                </Options>              

4.1.four. Installing Without Downloading¶

As some features of Python are not included in the initial installer download, selecting those features may require an internet connection. To avoid this demand, all possible components may be downloaded on-demand to create a complete layout that will no longer require an cyberspace connection regardless of the selected features. Notation that this download may be bigger than required, but where a big number of installations are going to be performed it is very useful to have a locally cached re-create.

Execute the following command from Control Prompt to download all possible required files. Remember to substitute python-iii.9.0.exe for the actual name of your installer, and to create layouts in their own directories to avoid collisions between files with the same name.

                python-3.9.0.exe /layout [optional target directory]              

You may also specify the /quiet option to hibernate the progress display.

4.1.5. Modifying an install¶

Once Python has been installed, you can add or remove features through the Programs and Features tool that is part of Windows. Select the Python entry and choose "Uninstall/Change" to open the installer in maintenance mode.

"Modify" allows you to add or remove features by modifying the checkboxes - unchanged checkboxes will non install or remove anything. Some options cannot exist changed in this mode, such as the install directory; to change these, you will need to remove and and so reinstall Python completely.

"Repair" will verify all the files that should be installed using the current settings and replace any that accept been removed or modified.

"Uninstall" will remove Python entirely, with the exception of the Python Launcher for Windows, which has its own entry in Programs and Features.

iv.two. The Microsoft Store parcel¶

New in version three.7.2.

The Microsoft Store package is an easily installable Python interpreter that is intended mainly for interactive employ, for example, by students.

To install the packet, ensure you accept the latest Windows ten updates and search the Microsoft Store app for "Python iii.10". Ensure that the app you lot select is published by the Python Software Foundation, and install it.

Warning

Python will e'er exist available for costless on the Microsoft Store. If you are asked to pay for it, you have not selected the correct package.

After installation, Python may exist launched by finding it in Start. Alternatively, it volition be available from any Command Prompt or PowerShell session by typing python . Farther, pip and IDLE may be used by typing pip or idle . IDLE can besides be establish in Start.

All iii commands are also available with version number suffixes, for example, as python3.exe and python3.x.exe as well as python.exe (where 3.ten is the specific version y'all want to launch, such as iii.10). Open "Manage App Execution Aliases" through Beginning to select which version of Python is associated with each command. It is recommended to brand sure that pip and idle are consistent with whichever version of python is selected.

Virtual environments tin can exist created with python -m venv and activated and used as normal.

If you have installed some other version of Python and added it to your PATH variable, it will be bachelor as python.exe rather than the one from the Microsoft Store. To access the new installation, apply python3.exe or python3.x.exe .

The py.exe launcher will discover this Python installation, but will adopt installations from the traditional installer.

To remove Python, open Settings and use Apps and Features, or else discover Python in Start and right-click to select Uninstall. Uninstalling volition remove all packages you installed direct into this Python installation, but will non remove any virtual environments

4.2.i. Known Issues¶

Because of restrictions on Microsoft Store apps, Python scripts may non have total write access to shared locations such equally TEMP and the registry. Instead, it will write to a private copy. If your scripts must change the shared locations, yous volition need to install the total installer.

For more detail on the technical basis for these limitations, please consult Microsoft's documentation on packaged full-trust apps, currently available at docs.microsoft.com/en-the states/windows/msix/desktop/desktop-to-uwp-behind-the-scenes

4.iii. The nuget.org packages¶

New in version 3.5.2.

The nuget.org package is a reduced size Python surroundings intended for use on continuous integration and build systems that do not take a organisation-wide install of Python. While nuget is "the package manager for .NET", it likewise works perfectly fine for packages containing build-time tools.

Visit nuget.org for the nearly up-to-date information on using nuget. What follows is a summary that is sufficient for Python developers.

The nuget.exe command line tool may exist downloaded direct from https://aka.ms/nugetclidl , for case, using curl or PowerShell. With the tool, the latest version of Python for 64-bit or 32-fleck machines is installed using:

              nuget.exe install python -ExcludeVersion -OutputDirectory . nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory .            

To select a particular version, add a -Version 3.x.y . The output directory may be changed from . , and the parcel volition be installed into a subdirectory. By default, the subdirectory is named the aforementioned as the package, and without the -ExcludeVersion option this proper name volition include the specific version installed. Inside the subdirectory is a tools directory that contains the Python installation:

                            # Without -ExcludeVersion              >              .\python.3.five.2\tools\python.exe -5              Python three.v.ii              # With -ExcludeVersion              >              .\python\tools\python.exe -Five              Python three.5.2            

In full general, nuget packages are non upgradeable, and newer versions should exist installed side-past-side and referenced using the full path. Alternatively, delete the package directory manually and install information technology again. Many CI systems will do this automatically if they practise not preserve files betwixt builds.

Alongside the tools directory is a build\native directory. This contains a MSBuild properties file python.props that can be used in a C++ projection to reference the Python install. Including the settings will automatically use the headers and import libraries in your build.

The bundle information pages on nuget.org are www.nuget.org/packages/python for the 64-chip version and world wide web.nuget.org/packages/pythonx86 for the 32-bit version.

four.4. The embeddable parcel¶

New in version 3.5.

The embedded distribution is a ZIP file containing a minimal Python surroundings. It is intended for interim as role of another application, rather than existence directly accessed by end-users.

When extracted, the embedded distribution is (almost) fully isolated from the user'southward system, including environment variables, organisation registry settings, and installed packages. The standard library is included as pre-compiled and optimized .pyc files in a ZIP, and python3.dll , python37.dll , python.exe and pythonw.exe are all provided. Tcl/tk (including all dependants, such as Idle), pip and the Python documentation are non included.

Note

The embedded distribution does not include the Microsoft C Runtime and it is the responsibility of the application installer to provide this. The runtime may take already been installed on a user'south system previously or automatically via Windows Update, and can be detected by finding ucrtbase.dll in the arrangement directory.

3rd-political party packages should be installed by the application installer alongside the embedded distribution. Using pip to manage dependencies as for a regular Python installation is not supported with this distribution, though with some care information technology may be possible to include and apply pip for automatic updates. In general, third-party packages should be treated as part of the application ("vendoring") and so that the developer can ensure compatibility with newer versions before providing updates to users.

The two recommended use cases for this distribution are described below.

iv.4.ane. Python Awarding¶

An application written in Python does not necessarily require users to be enlightened of that fact. The embedded distribution may exist used in this example to include a individual version of Python in an install packet. Depending on how transparent information technology should exist (or conversely, how professional information technology should appear), there are two options.

Using a specialized executable as a launcher requires some coding, just provides the well-nigh transparent feel for users. With a customized launcher, at that place are no obvious indications that the program is running on Python: icons tin can be customized, visitor and version information tin can exist specified, and file associations behave properly. In most cases, a custom launcher should simply be able to call Py_Main with a hard-coded command line.

The simpler approach is to provide a batch file or generated shortcut that straight calls the python.exe or pythonw.exe with the required command-line arguments. In this case, the application will appear to be Python and not its actual proper noun, and users may take trouble distinguishing it from other running Python processes or file associations.

With the latter approach, packages should exist installed equally directories alongside the Python executable to ensure they are available on the path. With the specialized launcher, packages tin be located in other locations as there is an opportunity to specify the search path before launching the application.

4.4.2. Embedding Python¶

Applications written in native code frequently require some form of scripting language, and the embedded Python distribution can be used for this purpose. In general, the majority of the awarding is in native code, and some part will either invoke python.exe or directly use python3.dll . For either case, extracting the embedded distribution to a subdirectory of the application installation is sufficient to provide a loadable Python interpreter.

As with the application use, packages tin be installed to whatsoever location every bit there is an opportunity to specify search paths before initializing the interpreter. Otherwise, in that location is no fundamental differences between using the embedded distribution and a regular installation.

four.v. Culling bundles¶

Too the standard CPython distribution, there are modified packages including boosted functionality. The post-obit is a listing of popular versions and their primal features:

ActivePython

Installer with multi-platform compatibility, documentation, PyWin32

Anaconda

Popular scientific modules (such as numpy, scipy and pandas) and the conda package manager.

Awning

A "comprehensive Python analysis environment" with editors and other development tools.

WinPython

Windows-specific distribution with prebuilt scientific packages and tools for edifice packages.

Note that these packages may not include the latest versions of Python or other libraries, and are not maintained or supported by the core Python team.

4.6. Configuring Python¶

To run Python conveniently from a command prompt, yous might consider changing some default environment variables in Windows. While the installer provides an option to configure the PATH and PATHEXT variables for you, this is only reliable for a unmarried, organisation-wide installation. If y'all regularly use multiple versions of Python, consider using the Python Launcher for Windows.

4.6.one. Excursus: Setting surroundings variables¶

Windows allows environs variables to be configured permanently at both the User level and the Organization level, or temporarily in a command prompt.

To temporarily set environment variables, open Command Prompt and use the ready command:

                                C:\>                set                PATH                =C:\Program Files\Python 3.nine;%PATH%                C:\>                set                PYTHONPATH                =                %PYTHONPATH%;C:\My_python_lib                C:\>python              

These changes volition apply to whatsoever farther commands executed in that console, and volition be inherited by any applications started from the panel.

Including the variable proper name inside percentage signs will expand to the existing value, allowing you lot to add together your new value at either the first or the finish. Modifying PATH by adding the directory containing python.exe to the start is a common way to ensure the correct version of Python is launched.

To permanently change the default environs variables, click Start and search for 'edit environment variables', or open up System properties, Avant-garde system settings and click the Environment Variables button. In this dialog, yous can add or alter User and System variables. To alter Organisation variables, you need not-restricted access to your machine (i.e. Administrator rights).

Note

Windows volition concatenate User variables after System variables, which may cause unexpected results when modifying PATH .

The PYTHONPATH variable is used by all versions of Python, so you should not permanently configure it unless the listed paths merely include code that is compatible with all of your installed Python versions.

four.6.2. Finding the Python executable¶

Changed in version 3.five.

Besides using the automatically created start bill of fare entry for the Python interpreter, you might desire to start Python in the command prompt. The installer has an option to set that upwards for you.

On the first page of the installer, an option labelled "Add Python to PATH" may be selected to have the installer add together the install location into the PATH . The location of the Scripts\ binder is too added. This allows you lot to blazon python to run the interpreter, and pip for the packet installer. Thus, y'all tin can also execute your scripts with command line options, see Command line documentation.

If you don't enable this option at install fourth dimension, you tin e'er re-run the installer, select Change, and enable it. Alternatively, y'all tin can manually modify the PATH using the directions in Excursus: Setting surround variables. You need to set up your PATH environment variable to include the directory of your Python installation, delimited past a semicolon from other entries. An example variable could look like this (assuming the first 2 entries already existed):

                C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.nine              

four.7. UTF-eight way¶

New in version iii.7.

Windows still uses legacy encodings for the arrangement encoding (the ANSI Code Folio). Python uses information technology for the default encoding of text files (e.chiliad. locale.getpreferredencoding() ).

This may cause bug because UTF-8 is widely used on the internet and nearly Unix systems, including WSL (Windows Subsystem for Linux).

You can apply the Python UTF-8 Manner to change the default text encoding to UTF-eight. Y'all tin can enable the Python UTF-8 Mode via the -X utf8 command line option, or the PYTHONUTF8=1 surroundings variable. Run across PYTHONUTF8 for enabling UTF-8 mode, and Excursus: Setting environs variables for how to modify environment variables.

When the Python UTF-8 Mode is enabled, you tin however use the system encoding (the ANSI Code Page) via the "mbcs" codec.

Note that calculation PYTHONUTF8=ane to the default environment variables will affect all Python 3.7+ applications on your organisation. If you have any Python 3.7+ applications which rely on the legacy organisation encoding, it is recommended to set the environment variable temporarily or use the -X utf8 command line pick.

Notation

Even when UTF-8 style is disabled, Python uses UTF-8 by default on Windows for:

  • Console I/O including standard I/O (see PEP 528 for details).

  • The filesystem encoding (see PEP 529 for details).

4.8. Python Launcher for Windows¶

New in version 3.3.

The Python launcher for Windows is a utility which aids in locating and executing of dissimilar Python versions. It allows scripts (or the control-line) to indicate a preference for a specific Python version, and will locate and execute that version.

Different the PATH variable, the launcher will correctly select the most appropriate version of Python. It will adopt per-user installations over organisation-wide ones, and orders by language version rather than using the near recently installed version.

The launcher was originally specified in PEP 397.

four.8.1. Getting started¶

four.8.1.ane. From the command-line¶

Inverse in version 3.6.

Organization-wide installations of Python 3.iii and later volition put the launcher on your PATH . The launcher is compatible with all bachelor versions of Python, so it does non matter which version is installed. To check that the launcher is available, execute the following command in Control Prompt:

You should find that the latest version of Python you take installed is started - it can be exited as normal, and any boosted command-line arguments specified will be sent straight to Python.

If you lot have multiple versions of Python installed (e.chiliad., iii.vii and three.10) y'all will take noticed that Python iii.10 was started - to launch Python 3.vii, try the command:

If you lot desire the latest version of Python 2 you accept installed, attempt the command:

You should detect the latest version of Python three.ten starts.

If you see the post-obit error, yous do not take the launcher installed:

                  'py' is not recognized every bit an internal or external command, operable program or batch file.                

Per-user installations of Python do not add the launcher to PATH unless the selection was selected on installation.

The command:

displays the currently installed version(s) of Python.

iv.8.i.2. Virtual environments¶

New in version 3.5.

If the launcher is run with no explicit Python version specification, and a virtual environment (created with the standard library venv module or the external virtualenv tool) active, the launcher will run the virtual environs's interpreter rather than the global i. To run the global interpreter, either deactivate the virtual environment, or explicitly specify the global Python version.

four.8.1.3. From a script¶

Permit'southward create a test Python script - create a file called hi.py with the following contents

                                    #! python                  import                  sys                  sys                  .                  stdout                  .                  write                  (                  "hello from Python                                    %s                  \n                  "                  %                  (                  sys                  .                  version                  ,))                

From the directory in which how-do-you-do.py lives, execute the control:

Y'all should notice the version number of your latest Python ii.ten installation is printed. Now try irresolute the outset line to exist:

Re-executing the command should at present impress the latest Python 3.x data. As with the in a higher place control-line examples, you tin can specify a more than explicit version qualifier. Assuming you have Python three.7 installed, try changing the first line to #! python3.vii and you should find the 3.10 version information printed.

Note that unlike interactive utilise, a bare "python" will utilise the latest version of Python 2.x that you lot take installed. This is for backward compatibility and for compatibility with Unix, where the command python typically refers to Python 2.

4.eight.i.4. From file associations¶

The launcher should accept been associated with Python files (i.eastward. .py , .pyw , .pyc files) when information technology was installed. This means that when you double-click on one of these files from Windows explorer the launcher will be used, and therefore y'all can use the same facilities described above to have the script specify the version which should be used.

The primal benefit of this is that a single launcher tin support multiple Python versions at the same time depending on the contents of the first line.

4.8.2. Shebang Lines¶

If the kickoff line of a script file starts with #! , it is known as a "shebang" line. Linux and other Unix like operating systems have native support for such lines and they are commonly used on such systems to indicate how a script should be executed. This launcher allows the aforementioned facilities to exist used with Python scripts on Windows and the examples above demonstrate their apply.

To let shebang lines in Python scripts to be portable betwixt Unix and Windows, this launcher supports a number of 'virtual' commands to specify which interpreter to use. The supported virtual commands are:

  • /usr/bin/env python

  • /usr/bin/python

  • /usr/local/bin/python

  • python

For example, if the first line of your script starts with

The default Python will exist located and used. As many Python scripts written to work on Unix will already have this line, you should observe these scripts can be used past the launcher without modification. If you lot are writing a new script on Windows which you hope will be useful on Unix, you lot should use i of the shebang lines starting with /usr .

Any of the above virtual commands can be suffixed with an explicit version (either just the major version, or the major and minor version). Furthermore the 32-bit version can be requested by adding "-32" after the modest version. I.east. /usr/bin/python3.seven-32 will asking usage of the 32-fleck python 3.seven.

New in version three.7: Beginning with python launcher 3.7 it is possible to asking 64-bit version by the "-64" suffix. Furthermore it is possible to specify a major and architecture without minor (i.east. /usr/bin/python3-64 ).

The /usr/bin/env form of shebang line has one further special property. Before looking for installed Python interpreters, this grade will search the executable PATH for a Python executable. This corresponds to the behaviour of the Unix env program, which performs a PATH search.

4.viii.3. Arguments in shebang lines¶

The shebang lines can besides specify boosted options to be passed to the Python interpreter. For example, if you have a shebang line:

Then Python volition be started with the -five option

4.viii.4. Customization¶

4.8.4.1. Customization via INI files¶

Two .ini files will exist searched past the launcher - py.ini in the current user's "application data" directory (i.e. the directory returned by calling the Windows office SHGetFolderPath with CSIDL_LOCAL_APPDATA ) and py.ini in the same directory as the launcher. The same .ini files are used for both the 'console' version of the launcher (i.eastward. py.exe) and for the 'windows' version (i.e. pyw.exe).

Customization specified in the "application directory" will accept precedence over the 1 next to the executable, so a user, who may not have write admission to the .ini file next to the launcher, can override commands in that global .ini file.

4.viii.4.2. Customizing default Python versions¶

In some cases, a version qualifier tin be included in a command to dictate which version of Python will be used past the control. A version qualifier starts with a major version number and tin can optionally exist followed by a period ('.') and a small version specifier. Furthermore information technology is possible to specify if a 32 or 64 bit implementation shall be requested past calculation "-32" or "-64".

For instance, a shebang line of #!python has no version qualifier, while #!python3 has a version qualifier which specifies just a major version.

If no version qualifiers are found in a command, the surround variable PY_PYTHON tin be prepare to specify the default version qualifier. If it is non set, the default is "iii". The variable tin specify any value that may be passed on the command line, such equally "iii", "iii.vii", "3.7-32" or "3.seven-64". (Notation that the "-64" option is but available with the launcher included with Python three.seven or newer.)

If no minor version qualifiers are found, the environment variable PY_PYTHON{major} (where {major} is the current major version qualifier as adamant above) tin exist fix to specify the full version. If no such option is constitute, the launcher volition enumerate the installed Python versions and apply the latest minor release found for the major version, which is probable, although not guaranteed, to be the most recently installed version in that family.

On 64-scrap Windows with both 32-bit and 64-flake implementations of the same (major.minor) Python version installed, the 64-bit version will always exist preferred. This will be true for both 32-fleck and 64-bit implementations of the launcher - a 32-bit launcher will prefer to execute a 64-bit Python installation of the specified version if bachelor. This is then the behavior of the launcher tin be predicted knowing merely what versions are installed on the PC and without regard to the order in which they were installed (i.e., without knowing whether a 32 or 64-flake version of Python and corresponding launcher was installed last). As noted above, an optional "-32" or "-64" suffix can be used on a version specifier to modify this behaviour.

Examples:

  • If no relevant options are gear up, the commands python and python2 will use the latest Python 2.x version installed and the command python3 will use the latest Python iii.x installed.

  • The command python3.7 volition non consult any options at all as the versions are fully specified.

  • If PY_PYTHON=3 , the commands python and python3 will both use the latest installed Python three version.

  • If PY_PYTHON=three.seven-32 , the command python will utilize the 32-chip implementation of 3.7 whereas the command python3 will utilize the latest installed Python (PY_PYTHON was not considered at all as a major version was specified.)

  • If PY_PYTHON=3 and PY_PYTHON3=iii.7 , the commands python and python3 volition both utilize specifically three.7

In improver to environment variables, the same settings tin can exist configured in the .INI file used past the launcher. The department in the INI file is called [defaults] and the cardinal proper name will be the same equally the environment variables without the leading PY_ prefix (and annotation that the key names in the INI file are example insensitive.) The contents of an environment variable will override things specified in the INI file.

For example:

  • Setting PY_PYTHON=3.7 is equivalent to the INI file containing:

  • Setting PY_PYTHON=3 and PY_PYTHON3=3.7 is equivalent to the INI file containing:

                                    [defaults]                                    python                  =                  3                                    python3                  =                  3.vii                                  

four.8.v. Diagnostics¶

If an environment variable PYLAUNCH_DEBUG is set (to whatsoever value), the launcher will impress diagnostic information to stderr (i.eastward. to the console). While this information manages to be simultaneously verbose and terse, it should allow you to see what versions of Python were located, why a particular version was chosen and the exact control-line used to execute the target Python.

4.9. Finding modules¶

Python normally stores its library (and thereby your site-packages folder) in the installation directory. So, if you had installed Python to C:\Python\ , the default library would reside in C:\Python\Lib\ and third-party modules should be stored in C:\Python\Lib\site-packages\ .

To completely override sys.path , create a ._pth file with the aforementioned proper name as the DLL ( python37._pth ) or the executable ( python._pth ) and specify ane line for each path to add to sys.path . The file based on the DLL name overrides the one based on the executable, which allows paths to exist restricted for any program loading the runtime if desired.

When the file exists, all registry and environs variables are ignored, isolated mode is enabled, and site is non imported unless i line in the file specifies import site . Blank paths and lines starting with # are ignored. Each path may be accented or relative to the location of the file. Import statements other than to site are non permitted, and capricious code cannot be specified.

Note that .pth files (without leading underscore) will be processed unremarkably by the site module when import site has been specified.

When no ._pth file is institute, this is how sys.path is populated on Windows:

  • An empty entry is added at the offset, which corresponds to the current directory.

  • If the environment variable PYTHONPATH exists, every bit described in Environment variables, its entries are added next. Note that on Windows, paths in this variable must be separated by semicolons, to distinguish them from the colon used in drive identifiers ( C:\ etc.).

  • Additional "application paths" can exist added in the registry as subkeys of \SOFTWARE\Python\PythonCore{version}\PythonPath under both the HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE hives. Subkeys which take semicolon-delimited path strings as their default value will cause each path to be added to sys.path . (Notation that all known installers only employ HKLM, so HKCU is typically empty.)

  • If the environment variable PYTHONHOME is set, it is assumed every bit "Python Home". Otherwise, the path of the main Python executable is used to locate a "landmark file" (either Lib\bone.py or pythonXY.zip ) to deduce the "Python Home". If a Python habitation is plant, the relevant sub-directories added to sys.path ( Lib , plat-win , etc) are based on that folder. Otherwise, the core Python path is constructed from the PythonPath stored in the registry.

  • If the Python Home cannot be located, no PYTHONPATH is specified in the environment, and no registry entries can exist found, a default path with relative entries is used (due east.thou. .\Lib;.\plat-win , etc).

If a pyvenv.cfg file is found aslope the main executable or in the directory one level above the executable, the following variations apply:

  • If dwelling is an accented path and PYTHONHOME is not gear up, this path is used instead of the path to the main executable when deducing the home location.

The end effect of all this is:

  • When running python.exe , or any other .exe in the chief Python directory (either an installed version, or directly from the PCbuild directory), the core path is deduced, and the core paths in the registry are ignored. Other "application paths" in the registry are always read.

  • When Python is hosted in another .exe (unlike directory, embedded via COM, etc), the "Python Domicile" will not be deduced, and so the core path from the registry is used. Other "awarding paths" in the registry are e'er read.

  • If Python can't find its dwelling house and there are no registry value (frozen .exe, some very strange installation setup) you become a path with some default, but relative, paths.

For those who want to bundle Python into their awarding or distribution, the following advice will prevent conflicts with other installations:

  • Include a ._pth file aslope your executable containing the directories to include. This will ignore paths listed in the registry and surroundings variables, and also ignore site unless import site is listed.

  • If you are loading python3.dll or python37.dll in your own executable, explicitly call Py_SetPath() or (at least) Py_SetProgramName() earlier Py_Initialize() .

  • Clear and/or overwrite PYTHONPATH and gear up PYTHONHOME earlier launching python.exe from your application.

  • If y'all cannot apply the previous suggestions (for instance, you are a distribution that allows people to run python.exe directly), ensure that the landmark file ( Lib\os.py ) exists in your install directory. (Note that it will not be detected inside a ZIP file, but a correctly named ZIP file will be detected instead.)

These will ensure that the files in a organisation-wide installation volition not take precedence over the re-create of the standard library bundled with your application. Otherwise, your users may experience problems using your application. Annotation that the get-go suggestion is the best, as the others may withal be susceptible to non-standard paths in the registry and user site-packages.

Changed in version three.6:

  • Adds ._pth file support and removes applocal pick from pyvenv.cfg .

  • Adds pythonXX.nothing as a potential landmark when directly adjacent to the executable.

Deprecated since version three.half-dozen:

Modules specified in the registry under Modules (not PythonPath ) may be imported by importlib.machinery.WindowsRegistryFinder . This finder is enabled on Windows in iii.6.0 and earlier, but may demand to be explicitly added to sys.meta_path in the future.

four.ten. Additional modules¶

Even though Python aims to be portable among all platforms, there are features that are unique to Windows. A couple of modules, both in the standard library and external, and snippets exist to use these features.

The Windows-specific standard modules are documented in MS Windows Specific Services.

4.10.one. PyWin32¶

The PyWin32 module by Mark Hammond is a collection of modules for advanced Windows-specific back up. This includes utilities for:

  • Component Object Model (COM)

  • Win32 API calls

  • Registry

  • Issue log

  • Microsoft Foundation Classes (MFC) user interfaces

PythonWin is a sample MFC awarding shipped with PyWin32. It is an embeddable IDE with a built-in debugger.

4.x.2. cx_Freeze¶

cx_Freeze is a distutils extension (see Extending Distutils) which wraps Python scripts into executable Windows programs ( * .exe files). When y'all have washed this, yous can distribute your application without requiring your users to install Python.

4.11. Compiling Python on Windows¶

If you lot want to compile CPython yourself, first thing you should do is get the source. Yous can download either the latest release'southward source or simply grab a fresh checkout.

The source tree contains a build solution and project files for Microsoft Visual Studio, which is the compiler used to build the official Python releases. These files are in the PCbuild directory.

Check PCbuild/readme.txt for general information on the build procedure.

For extension modules, consult Building C and C++ Extensions on Windows.

four.12. Other Platforms¶

With ongoing development of Python, some platforms that used to be supported earlier are no longer supported (due to the lack of users or developers). Check PEP eleven for details on all unsupported platforms.

  • Windows CE is no longer supported since Python 3 (if it e'er was).

  • The Cygwin installer offers to install the Python interpreter equally well

See Python for Windows for detailed data virtually platforms with pre-compiled installers.