four. Using Python on Windows¶

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

Unlike most Unix systems and services, Windows does not include a system supported installation of Python. To make Python available, the CPython team 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 cadre interpreter and library being used by a single user. The installer is likewise able to install for all users of a single motorcar, and a split up Cipher file is bachelor for application-local distributions.

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

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

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

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

The nuget.org packages are lightweight installations intended for continuous integration systems. Information technology 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.ane. The full installer¶

4.1.i. Installation steps¶

Four Python 3.x installers are available for download - two each for the 32-bit and 64-chip versions of the interpreter. The web installer is a modest initial download, and information technology will automatically download the required components equally necessary. The offline installer includes the components necessary for a default installation and only requires an cyberspace connection for optional features. See Installing Without Downloading for other means to avoid downloading during installation.

Afterwards starting the installer, 1 of two options may be selected:

../_images/win_installer.png

If you select "Install At present":

  • You will not need to be an administrator (unless a system update for the C Runtime Library is required or you install the Python Launcher for Windows for all users)

  • Python volition be installed into your user directory

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

  • The standard library, exam suite, launcher and pip will exist installed

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

  • Shortcuts will only be visible for the current user

Selecting "Customize installation" will allow you to select the features to install, the installation location and other options or post-install actions. To install debugging symbols or binaries, yous will demand to employ this option.

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

  • You may exist required to provide authoritative credentials or approval

  • Python volition exist installed into the Program Files directory

  • The Python Launcher for Windows will exist 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 volition be added to the system PATH

  • Shortcuts are available for all users

iv.1.2. Removing the MAX_PATH Limitation¶

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

In the latest versions of Windows, this limitation can be expanded to approximately 32,000 characters. Your administrator will demand to activate the "Enable Win32 long paths" group policy, or set LongPathsEnabled to ane in the registry central HKEY_LOCAL_MACHINE\Arrangement\CurrentControlSet\Control\FileSystem .

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

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

Changed in version three.6: 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 social club to change some of the defaults.

To completely hide the installer UI and install Python silently, pass the /quiet pick. To skip past the user interaction but even so brandish progress and errors, pass the /passive pick. The /uninstall option may be passed to immediately begin removing Python - no confirmation prompt will be displayed.

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

Proper noun

Clarification

Default

InstallAllUsers

Perform a arrangement-broad installation.

0

TargetDir

The installation directory

Selected based on InstallAllUsers

DefaultAllUsersTargetDir

The default installation directory for all-user installs

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

DefaultJustForMeTargetDir

The default install directory for just-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 too installed.

1

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

1

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.

1

InstallLauncherAllUsers

Installs Python Launcher for Windows for all users.

1

Include_lib

Install standard library and extension modules

one

Include_pip

Install arranged pip and setuptools

1

Include_symbols

Install debugging symbols (*.pdb)

0

Include_tcltk

Install Tcl/Tk back up and IDLE

1

Include_test

Install standard library examination suite

1

Include_tools

Install utility scripts

one

LauncherOnly

Only installs the launcher. This will override most other options.

0

SimpleInstall

Disable virtually install UI

0

SimpleInstallDescription

A custom bulletin to brandish when the simplified install UI is used.

(empty)

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

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

To allow users to easily install a personal copy of Python without the test suite, you lot could provide a shortcut with the following command. This will display a simplified initial page and disallow customization:

                python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0     SimpleInstall=i SimpleInstallDescription="Only for me, no test suite."              

(Notation that omitting the launcher as well omits file associations, and is merely recommended for per-user installs when there is also a system-wide installation that included the launcher.)

The options listed above can as well exist provided in a file named unattend.xml alongside the executable. This file specifies a list of options and values. When a value is provided as an attribute, it will be converted to a number if possible. Values provided as element text are ever left as strings. This example file sets the aforementioned options as the previous case:

                                <Options>                <Selection                Proper name=                "InstallAllUsers"                Value=                "no"                />                <Option                Name=                "Include_launcher"                Value=                "0"                />                <Selection                Proper noun=                "Include_test"                Value=                "no"                />                <Option                Name=                "SimpleInstall"                Value=                "yes"                />                <Option                Proper name=                "SimpleInstallDescription"                >Just for me, no test suite</Selection>                </Options>              

4.1.iv. Installing Without Downloading¶

Every bit some features of Python are not included in the initial installer download, selecting those features may require an internet connection. To avert this need, all possible components may exist downloaded on-demand to create a consummate layout that will no longer crave an internet connection regardless of the selected features. Note that this download may be bigger than required, but where a big number of installations are going to be performed information technology is very useful to have a locally cached re-create.

Execute the following command from Command Prompt to download all possible required files. Recall to substitute python-three.nine.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-three.9.0.exe /layout [optional target directory]              

Y'all may also specify the /quiet choice to hide the progress brandish.

4.ane.5. Modifying an install¶

In one case 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 cull "Uninstall/Alter" to open up the installer in maintenance mode.

"Modify" allows you to add or remove features by modifying the checkboxes - unchanged checkboxes volition non install or remove anything. Some options cannot be changed in this mode, such as the install directory; to modify these, yous 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 whatsoever that accept been removed or modified.

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

4.2. The Microsoft Shop packet¶

New in version iii.7.2.

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

To install the package, ensure you accept the latest Windows 10 updates and search the Microsoft Shop app for "Python 3.x". Ensure that the app you select is published by the Python Software Foundation, and install information technology.

Alarm

Python will always exist available for free on the Microsoft Shop. If you are asked to pay for it, y'all have not selected the correct package.

Later on installation, Python may be launched by finding information technology in Start. Alternatively, it will be available from any Command Prompt or PowerShell session by typing python . Further, pip and IDLE may be used past typing pip or idle . IDLE can also be found in First.

All three commands are also bachelor with version number suffixes, for instance, as python3.exe and python3.10.exe besides as python.exe (where 3.x is the specific version you desire to launch, such every bit 3.10). Open "Manage App Execution Aliases" through Start 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 can be created with python -m venv and activated and used as normal.

If you have installed another version of Python and added it to your PATH variable, it will exist bachelor equally python.exe rather than the one from the Microsoft Store. To access the new installation, utilise python3.exe or python3.x.exe .

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

To remove Python, open up Settings and utilize Apps and Features, or else find Python in First and right-click to select Uninstall. Uninstalling will remove all packages you installed direct into this Python installation, but will not remove any virtual environments

4.two.one. Known Issues¶

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

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

4.3. The nuget.org packages¶

New in version 3.5.2.

The nuget.org package is a reduced size Python environment intended for use on continuous integration and build systems that do not accept a system-wide install of Python. While nuget is "the package managing director for .Cyberspace", it too works perfectly fine for packages containing build-time tools.

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

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

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

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

              # Without -ExcludeVersion > .\python.3.5.ii\tools\python.exe -V Python three.5.ii  # With -ExcludeVersion > .\python\tools\python.exe -Five Python 3.v.ii            

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

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

The package information pages on nuget.org are www.nuget.org/packages/python for the 64-bit version and www.nuget.org/packages/pythonx86 for the 32-fleck version.

four.4. The embeddable package¶

New in version 3.5.

The embedded distribution is a ZIP file containing a minimal Python environment. Information technology is intended for acting as office of another application, rather than existence direct accessed by end-users.

When extracted, the embedded distribution is (virtually) fully isolated from the user's system, including environment variables, organisation registry settings, and installed packages. The standard library is included equally 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 not 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 have already been installed on a user's system previously or automatically via Windows Update, and tin be detected past finding ucrtbase.dll in the organisation directory.

Tertiary-party packages should exist installed past the awarding installer aslope the embedded distribution. Using pip to manage dependencies as for a regular Python installation is non supported with this distribution, though with some care it may exist possible to include and use pip for automatic updates. In full general, 3rd-political party packages should be treated equally part of the application ("vendoring") and then that the developer tin ensure compatibility with newer versions before providing updates to users.

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

4.four.i. Python Application¶

An awarding written in Python does not necessarily crave users to be aware of that fact. The embedded distribution may be used in this example to include a private version of Python in an install package. Depending on how transparent it should be (or conversely, how professional information technology should appear), in that location are ii options.

Using a specialized executable as a launcher requires some coding, but provides the most transparent experience for users. With a customized launcher, there are no obvious indications that the program is running on Python: icons can be customized, company and version information can be specified, and file associations conduct properly. In near cases, a custom launcher should but exist able to telephone call Py_Main with a hard-coded control line.

The simpler approach is to provide a batch file or generated shortcut that directly calls the python.exe or pythonw.exe with the required command-line arguments. In this case, the application volition appear to be Python and not its bodily name, and users may accept trouble distinguishing information technology from other running Python processes or file associations.

With the latter approach, packages should exist installed as directories alongside the Python executable to ensure they are bachelor on the path. With the specialized launcher, packages can be located in other locations as in that location is an opportunity to specify the search path before launching the awarding.

4.iv.2. Embedding Python¶

Applications written in native code ofttimes require some course 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 example, extracting the embedded distribution to a subdirectory of the awarding installation is sufficient to provide a loadable Python interpreter.

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

4.5. Alternative bundles¶

Likewise the standard CPython distribution, at that place are modified packages including additional functionality. The following is a list of pop versions and their key features:

ActivePython

Installer with multi-platform compatibility, documentation, PyWin32

Anaconda

Popular scientific modules (such every bit numpy, scipy and pandas) and the conda package director.

Canopy

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

4.6. Configuring Python¶

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

four.6.1. Excursus: Setting environs variables¶

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

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

                                C:\>                prepare                PATH                =C:\Program Files\Python 3.9;%PATH%                C:\>                set                PYTHONPATH                =                %PYTHONPATH%;C:\My_python_lib                C:\>python              

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

Including the variable proper name within pct signs will aggrandize to the existing value, allowing you to add your new value at either the showtime or the end. Modifying PATH past adding the directory containing python.exe to the beginning is a common way to ensure the correct version of Python is launched.

To permanently modify the default surroundings variables, click Start and search for 'edit environment variables', or open up System properties, Advanced system settings and click the Environment Variables push. In this dialog, you can add or modify User and System variables. To change System variables, you need non-restricted admission to your machine (i.eastward. Administrator rights).

Note

Windows volition concatenate User variables after Organization variables, which may crusade unexpected results when modifying PATH .

The PYTHONPATH variable is used past all versions of Python 2 and Python 3, so you should not permanently configure this variable unless it merely includes code that is compatible with all of your installed Python versions.

4.half dozen.2. Finding the Python executable¶

Changed in version three.five.

Besides using the automatically created starting time bill of fare entry for the Python interpreter, yous might want to first Python in the command prompt. The installer has an pick to set that up for yous.

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\ folder is as well added. This allows yous to type python to run the interpreter, and pip for the packet installer. Thus, you can also execute your scripts with command line options, encounter Command line documentation.

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

                C:\WINDOWS\system32;C:\WINDOWS;C:\Programme Files\Python 3.9              

4.7. UTF-8 mode¶

New in version iii.7.

Windows notwithstanding uses legacy encodings for the system encoding (the ANSI Lawmaking Folio). Python uses information technology for the default encoding of text files (e.one thousand. locale.getpreferredencoding() ).

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

You can use the Python UTF-8 Way to change the default text encoding to UTF-8. You can enable the Python UTF-8 Mode via the -Ten utf8 command line option, or the PYTHONUTF8=1 environment variable. Come across PYTHONUTF8 for enabling UTF-eight manner, and Excursus: Setting environment variables for how to modify environment variables.

When the Python UTF-8 Manner is enabled, you tin can nevertheless apply the system encoding (the ANSI Code Page) via the "mbcs" codec.

Note that adding PYTHONUTF8=1 to the default environment variables will affect all Python iii.vii+ applications on your organisation. If you take any Python 3.7+ applications which rely on the legacy system encoding, it is recommended to set the environment variable temporarily or utilize the -Ten utf8 control line option.

Note

Even when UTF-8 mode 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.iii.

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

Unlike the PATH variable, the launcher will correctly select the about advisable version of Python. It volition prefer per-user installations over organisation-wide ones, and orders by language version rather than using the about recently installed version.

The launcher was originally specified in PEP 397.

4.8.1. Getting started¶

iv.eight.i.1. From the command-line¶

Changed in version 3.6.

System-broad installations of Python 3.3 and subsequently volition put the launcher on your PATH . The launcher is uniform with all available versions of Python, and then it does not matter which version is installed. To check that the launcher is bachelor, execute the following control in Command Prompt:

You should find that the latest version of Python you have installed is started - it tin be exited every bit normal, and whatsoever boosted command-line arguments specified will be sent straight to Python.

If you have multiple versions of Python installed (due east.thou., 2.7 and 3.10) you will accept noticed that Python 3.ten was started - to launch Python 2.seven, effort the command:

If y'all want the latest version of Python 2.ten you accept installed, try the control:

You should detect the latest version of Python 2.10 starts.

If y'all run into the following mistake, y'all practise not have the launcher installed:

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

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

You lot should see the currently installed versions of Python.

iv.8.1.two. 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 volition run the virtual surroundings's interpreter rather than the global i. To run the global interpreter, either deactivate the virtual environment, or explicitly specify the global Python version.

4.eight.1.3. From a script¶

Let's create a test Python script - create a file called hello.py with the post-obit contents

                                    #! python                  import                  sys                  sys                  .                  stdout                  .                  write                  (                  "hullo from Python                                    %due south                  \north                  "                  %                  (                  sys                  .                  version                  ,))                

From the directory in which hello.py lives, execute the control:

You lot should detect the version number of your latest Python 2.10 installation is printed. Now try changing the first line to be:

Re-executing the control should now print the latest Python 3.x information. As with the above command-line examples, you can specify a more explicit version qualifier. Assuming you accept Python ii.half dozen installed, try changing the commencement line to #! python2.6 and you should observe the two.half-dozen version data printed.

Note that different interactive use, a blank "python" will employ the latest version of Python 2.x that y'all have installed. This is for backward compatibility and for compatibility with Unix, where the control python typically refers to Python two.

4.8.one.iv. From file associations¶

The launcher should have been associated with Python files (i.due east. .py , .pyw , .pyc files) when it was installed. This means that when you double-click on one of these files from Windows explorer the launcher will exist used, and therefore you tin use the same facilities described higher up to have the script specify the version which should exist used.

The cardinal benefit of this is that a single launcher can support multiple Python versions at the same fourth dimension depending on the contents of the beginning line.

4.8.2. Shebang Lines¶

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

To allow shebang lines in Python scripts to be portable between Unix and Windows, this launcher supports a number of 'virtual' commands to specify which interpreter to apply. 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 be located and used. Every bit many Python scripts written to piece of work on Unix will already take this line, you lot should notice these scripts tin can be used by the launcher without modification. If you are writing a new script on Windows which yous promise will be useful on Unix, you should employ ane of the shebang lines starting with /usr .

Whatever of the to a higher place virtual commands can be suffixed with an explicit version (either just the major version, or the major and modest version). Furthermore the 32-bit version can be requested by adding "-32" afterwards the minor version. I.east. /usr/bin/python2.seven-32 will request usage of the 32-flake python 2.7.

New in version iii.vii: Beginning with python launcher 3.seven it is possible to request 64-bit version by the "-64" suffix. Furthermore information technology is possible to specify a major and architecture without minor (i.e. /usr/bin/python3-64 ).

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

4.eight.3. Arguments in shebang lines¶

The shebang lines can also specify additional options to be passed to the Python interpreter. For instance, if y'all take a shebang line:

Then Python will be started with the -v option

iv.8.4. Customization¶

4.8.4.one. Customization via INI files¶

Two .ini files will be searched past the launcher - py.ini in the electric current user's "awarding data" directory (i.e. the directory returned by calling the Windows function 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.e. py.exe) and for the 'windows' version (i.e. pyw.exe).

Customization specified in the "application directory" will have precedence over the one next to the executable, then a user, who may not have write access to the .ini file next to the launcher, tin override commands in that global .ini file.

4.8.4.2. Customizing default Python versions¶

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

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

If no version qualifiers are plant in a control, the environment variable PY_PYTHON tin can exist set to specify the default version qualifier. If it is not set, the default is "3". The variable tin specify whatsoever value that may exist passed on the command line, such as "3", "3.vii", "iii.vii-32" or "3.vii-64". (Note that the "-64" choice is only bachelor with the launcher included with Python iii.7 or newer.)

If no minor version qualifiers are found, the environs variable PY_PYTHON{major} (where {major} is the electric current major version qualifier every bit determined above) tin can be set to specify the full version. If no such choice is establish, the launcher will enumerate the installed Python versions and employ the latest modest release found for the major version, which is likely, although non guaranteed, to be the most recently installed version in that family.

On 64-bit Windows with both 32-bit and 64-bit implementations of the same (major.minor) Python version installed, the 64-bit version will always be preferred. This volition be true for both 32-bit 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 available. This is so the behavior of the launcher tin can be predicted knowing only what versions are installed on the PC and without regard to the lodge in which they were installed (i.e., without knowing whether a 32 or 64-bit version of Python and corresponding launcher was installed terminal). Every bit noted above, an optional "-32" or "-64" suffix tin can be used on a version specifier to change this behaviour.

Examples:

  • If no relevant options are set, the commands python and python2 will utilize the latest Python 2.ten version installed and the command python3 volition use the latest Python 3.x installed.

  • The commands python3.one and python2.7 will not consult any options at all as the versions are fully specified.

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

  • If PY_PYTHON=3.1-32 , the control python will utilise the 32-fleck implementation of 3.1 whereas the command python3 will use the latest installed Python (PY_PYTHON was not considered at all as a major version was specified.)

  • If PY_PYTHON=three and PY_PYTHON3=3.1 , the commands python and python3 volition both use specifically 3.1

In addition to environment variables, the same settings can exist configured in the .INI file used by the launcher. The section in the INI file is called [defaults] and the central name will be the aforementioned as the surround variables without the leading PY_ prefix (and note that the key names in the INI file are case insensitive.) The contents of an environment variable will override things specified in the INI file.

For instance:

  • Setting PY_PYTHON=iii.one is equivalent to the INI file containing:

  • Setting PY_PYTHON=3 and PY_PYTHON3=three.1 is equivalent to the INI file containing:

                                    [defaults]                  python                  =                  three                  python3                  =                  iii.1                

iv.8.5. Diagnostics¶

If an environment variable PYLAUNCH_DEBUG is set (to any value), the launcher will print diagnostic information to stderr (i.e. 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 item version was chosen and the exact control-line used to execute the target Python.

4.nine. Finding modules¶

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

To completely override sys.path , create a ._pth file with the same name as the DLL ( python37._pth ) or the executable ( python._pth ) and specify ane line for each path to add together to sys.path . The file based on the DLL name overrides the ane based on the executable, which allows paths to be restricted for whatsoever programme loading the runtime if desired.

When the file exists, all registry and environs variables are ignored, isolated mode is enabled, and site is not imported unless 1 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 not permitted, and capricious code cannot exist specified.

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

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

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

  • If the surround variable PYTHONPATH exists, as described in Environment variables, its entries are added next. Notation 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 be 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 accept semicolon-delimited path strings as their default value volition cause each path to exist added to sys.path . (Note that all known installers but utilise HKLM, then HKCU is typically empty.)

  • If the environment variable PYTHONHOME is prepare, it is causeless every bit "Python Dwelling". Otherwise, the path of the principal Python executable is used to locate a "landmark file" (either Lib\os.py or pythonXY.nil ) to deduce the "Python Abode". If a Python home is found, 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 Habitation cannot be located, no PYTHONPATH is specified in the environment, and no registry entries tin be found, a default path with relative entries is used (e.g. .\Lib;.\plat-win , etc).

If a pyvenv.cfg file is constitute alongside the main executable or in the directory i level above the executable, the following variations utilise:

  • If dwelling house is an absolute path and PYTHONHOME is not set, this path is used instead of the path to the main executable when deducing the home location.

The end event of all this is:

  • When running python.exe , or whatever other .exe in the principal 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 "awarding paths" in the registry are e'er read.

  • When Python is hosted in some other .exe (different directory, embedded via COM, etc), the "Python Abode" will not be deduced, so the core path from the registry is used. Other "application paths" in the registry are always read.

  • If Python tin't find its home and there are no registry value (frozen .exe, some very strange installation setup) you lot get a path with some default, merely relative, paths.

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

  • Include a ._pth file alongside your executable containing the directories to include. This volition ignore paths listed in the registry and environment variables, and too ignore site unless import site is listed.

  • If you lot are loading python3.dll or python37.dll in your own executable, explicitly call Py_SetPath() or (at to the lowest degree) Py_SetProgramName() before Py_Initialize() .

  • Articulate and/or overwrite PYTHONPATH and ready PYTHONHOME before launching python.exe from your awarding.

  • If you cannot apply the previous suggestions (for example, you lot are a distribution that allows people to run python.exe directly), ensure that the landmark file ( Lib\os.py ) exists in your install directory. (Notation that it will not be detected inside a ZIP file, merely a correctly named Cypher file volition be detected instead.)

These will ensure that the files in a system-broad installation will not accept precedence over the copy of the standard library arranged with your application. Otherwise, your users may experience bug using your application. Note that the get-go proposition is the best, as the others may still 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 option from pyvenv.cfg .

  • Adds pythonXX.zip every bit a potential landmark when directly adjacent to the executable.

Deprecated since version 3.half-dozen:

Modules specified in the registry nether Modules (not PythonPath ) may be imported past importlib.mechanism.WindowsRegistryFinder . This finder is enabled on Windows in 3.half-dozen.0 and earlier, simply may demand to be explicitly added to sys.meta_path in the future.

4.10. Additional modules¶

Fifty-fifty 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 utilize these features.

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

iv.x.one. PyWin32¶

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

  • Component Object Model (COM)

  • Win32 API calls

  • Registry

  • Result log

  • Microsoft Foundation Classes (MFC) user interfaces

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

4.ten.ii. cx_Freeze¶

cx_Freeze is a distutils extension (see Extending Distutils) which wraps Python scripts into executable Windows programs ( * .exe files). When you have done this, you lot tin distribute your awarding without requiring your users to install Python.

4.10.iii. WConio¶

Since Python's advanced final treatment layer, curses , is restricted to Unix-like systems, there is a library sectional to Windows likewise: Windows Console I/O for Python.

WConio is a wrapper for Turbo-C's CONIO.H , used to create text user interfaces.

4.11. Compiling Python on Windows¶

If you desire to compile CPython yourself, first thing you should do is get the source. Yous can download either the latest release's source or just take hold of a fresh checkout.

The source tree contains a build solution and project files for Microsoft Visual Studio 2022, 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 process.

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

Come across too

Python + Windows + distutils + SWIG + gcc MinGW

or "Creating Python extensions in C/C++ with SWIG and compiling them with MinGW gcc under Windows" or "Installing Python extension with distutils and without Microsoft Visual C++" by Sébastien Sauvage, 2003

4.12. Other Platforms¶

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

  • Windows CE is however supported.

  • The Cygwin installer offers to install the Python interpreter too (cf. Cygwin bundle source, Maintainer releases)

Meet Python for Windows for detailed information about platforms with pre-compiled installers.