iv. Using Python on Windows¶

This document aims to give an overview of Windows-specific behaviour y'all should know about when using Python on Microsoft Windows.

Different virtually 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 too able to install for all users of a single machine, and a separate ZIP file is bachelor for awarding-local distributions.

As specified in PEP eleven, a Python release just supports a Windows platform while Microsoft considers the platform under extended support. This means that Python 3.10 supports Windows 8.i and newer. If you lot crave Windows 7 support, delight install Python 3.viii.

In that location are a number of unlike installers available 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 simple installation of Python that is suitable for running scripts and packages, and using IDLE or other development environments. It requires Windows ten, but can be 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 can be used to build Python packages or run scripts, but is not updateable and has no user interface tools.

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

four.one. The full installer¶

iv.1.one. Installation steps¶

Four Python iii.10 installers are bachelor for download - two each for the 32-scrap and 64-bit versions of the interpreter. The 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 only requires an internet connection for optional features. See Installing Without Downloading for other ways to avoid downloading during installation.

Afterward starting the installer, one of two options may be selected:

../_images/win_installer.png

If yous select "Install At present":

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

  • Python will be installed into your user directory

  • The Python Launcher for Windows will be installed according to the choice at the bottom of the offset page

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

  • If selected, the install directory will exist added to your PATH

  • Shortcuts will simply be visible for the current user

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

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

  • You lot may exist required to provide administrative credentials or approval

  • Python volition 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 volition be added to the system PATH

  • Shortcuts are bachelor for all users

4.1.2. Removing the MAX_PATH Limitation¶

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

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

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

Afterwards changing the in a higher place option, no further configuration is required.

Changed in version 3.6: Support for long paths was enabled in Python.

4.i.iii. 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 exist set without suppressing the UI in order to change some of the defaults.

To completely hibernate the installer UI and install Python silently, pass the /tranquillity option. To skip past the user interaction only however display progress and errors, pass the /passive pick. The /uninstall option may be passed to immediately begin removing Python - no confirmation prompt volition be displayed.

All other options are passed as name=value , where the value is ordinarily 0 to disable a feature, one to enable a feature, or a path. The full list of available options is shown beneath.

Proper noun

Description

Default

InstallAllUsers

Perform a system-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 Ten.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 also installed.

i

CompileAll

Compile all .py files to .pyc .

0

PrependPath

Add together 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 manual

ane

Include_debug

Install debug binaries

0

Include_dev

Install developer headers and libraries

1

Include_exe

Install python.exe and related files

i

Include_launcher

Install Python Launcher for Windows.

one

InstallLauncherAllUsers

Installs Python Launcher for Windows for all users.

1

Include_lib

Install standard library and extension modules

1

Include_pip

Install arranged pip and setuptools

1

Include_symbols

Install debugging symbols (*.pdb)

0

Include_tcltk

Install Tcl/Tk support and IDLE

1

Include_test

Install standard library test suite

1

Include_tools

Install utility scripts

1

LauncherOnly

Merely installs the launcher. This volition override well-nigh other options.

0

SimpleInstall

Disable almost install UI

0

SimpleInstallDescription

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

(empty)

For example, to silently install a default, organisation-wide Python installation, you could utilise the post-obit command (from an elevated command prompt):

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

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

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

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

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

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

4.1.4. 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 need, all possible components may be downloaded on-demand to create a complete layout that will no longer crave an internet connection regardless of the selected features. Notation that this download may be bigger than required, merely where a big number of installations are going to be performed it is very useful to have a locally buried copy.

Execute the following command from Control Prompt to download all possible required files. Recollect to substitute python-3.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 proper name.

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

You may too specify the /quiet option to hide the progress brandish.

iv.i.5. Modifying an install¶

One time Python has been installed, y'all can add together or remove features through the Programs and Features tool that is part of Windows. Select the Python entry and choose "Uninstall/Change" to open up the installer in maintenance fashion.

"Modify" allows you to add or remove features past modifying the checkboxes - unchanged checkboxes will not install or remove anything. Some options cannot be changed in this fashion, such as the install directory; to modify these, you will need to remove and so reinstall Python completely.

"Repair" volition verify all the files that should be installed using the current settings and replace whatsoever that have been removed or modified.

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

4.2. The Microsoft Store package¶

New in version three.7.2.

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

To install the package, ensure yous have the latest Windows 10 updates and search the Microsoft Store app for "Python 3.ten". Ensure that the app y'all select is published by the Python Software Foundation, and install information technology.

Warning

Python volition always be available for free on the Microsoft Shop. If you are asked to pay for it, you accept not selected the right parcel.

After installation, Python may be launched by finding it in Start. Alternatively, it volition exist available from any Control Prompt or PowerShell session by typing python . Further, pip and IDLE may exist used by typing pip or idle . IDLE can also be found in Start.

All three commands are also available with version number suffixes, for case, as python3.exe and python3.x.exe as well as python.exe (where 3.x is the specific version y'all desire to launch, such as 3.10). Open up "Manage App Execution Aliases" through First to select which version of Python is associated with each command. Information technology is recommended to make sure that pip and idle are consistent with whichever version of python is selected.

Virtual environments can be created with python -thousand venv and activated and used every bit normal.

If you lot have installed another version of Python and added it to your PATH variable, information technology will exist bachelor as python.exe rather than the ane from the Microsoft Store. To admission the new installation, employ python3.exe or python3.x.exe .

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

To remove Python, open Settings and use Apps and Features, or else find Python in Start and right-click to select Uninstall. Uninstalling will remove all packages you installed straight into this Python installation, but will not remove whatsoever virtual environments

four.ii.ane. Known Bug¶

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

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

4.3. The nuget.org packages¶

New in version 3.five.2.

The nuget.org parcel is a reduced size Python environment intended for utilise on continuous integration and build systems that exercise not have a system-wide install of Python. While nuget is "the bundle director for .NET", it too works perfectly fine for packages containing build-time tools.

Visit nuget.org for the near upwards-to-date data on using nuget. What follows is a summary that is sufficient for Python developers.

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

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

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

                            # Without -ExcludeVersion              >              .\python.iii.5.two\tools\python.exe -V              Python iii.5.2              # With -ExcludeVersion              >              .\python\tools\python.exe -V              Python 3.v.ii            

In general, nuget packages are non upgradeable, and newer versions should be installed side-by-side and referenced using the full path. Alternatively, delete the package directory manually and install it once more. Many CI systems volition exercise this automatically if they do non preserve files between 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 will automatically use the headers and import libraries in your build.

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

iv.4. The embeddable package¶

New in version 3.five.

The embedded distribution is a Naught file containing a minimal Python environment. It is intended for acting as part of another application, rather than beingness directly accessed by end-users.

When extracted, the embedded distribution is (most) fully isolated from the user'southward system, including environment variables, system 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 every bit Idle), pip and the Python documentation are non included.

Note

The embedded distribution does non 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'southward arrangement previously or automatically via Windows Update, and tin be detected by finding ucrtbase.dll in the organization directory.

Third-political party packages should be installed past 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 it may be possible to include and use pip for automatic updates. In full general, third-political party packages should be treated every bit office of the application ("vendoring") so that the developer can ensure compatibility with newer versions before providing updates to users.

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

4.four.ane. Python Application¶

An application written in Python does non necessarily require users to be aware of that fact. The embedded distribution may be used in this instance to include a private version of Python in an install package. Depending on how transparent it should be (or conversely, how professional it should appear), there are two options.

Using a specialized executable every bit 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 tin can be customized, company and version information can be specified, and file associations behave properly. In most cases, a custom launcher should just be able to call Py_Main with a hard-coded command line.

The simpler arroyo is to provide a batch file or generated shortcut that direct 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 actual name, and users may have problem distinguishing information technology from other running Python processes or file associations.

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

iv.4.2. Embedding Python¶

Applications written in native code often require some form of scripting language, and the embedded Python distribution can exist used for this purpose. In full general, the bulk of the application is in native code, and some office volition either invoke python.exe or directly utilise 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 utilize, packages can be installed to any location equally in that location is an opportunity to specify search paths earlier initializing the interpreter. Otherwise, there is no fundamental differences between using the embedded distribution and a regular installation.

4.five. Culling bundles¶

As well the standard CPython distribution, in that location are modified packages including boosted functionality. The post-obit is a list of popular versions and their key features:

ActivePython

Installer with multi-platform compatibility, documentation, PyWin32

Anaconda

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

Canopy

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

WinPython

Windows-specific distribution with prebuilt scientific packages and tools for building 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.

four.6. Configuring Python¶

To run Python conveniently from a command prompt, you might consider changing some default environs variables in Windows. While the installer provides an option to configure the PATH and PATHEXT variables for you, this is but reliable for a single, organization-wide installation. If you regularly use multiple versions of Python, consider using the Python Launcher for Windows.

four.six.one. Excursus: Setting environment variables¶

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

To temporarily gear up surroundings variables, open Command Prompt and use the gear up control:

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

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

Including the variable name within percent signs will expand to the existing value, allowing you to add your new value at either the outset or the end. Modifying PATH past adding the directory containing python.exe to the outset is a common mode to ensure the right version of Python is launched.

To permanently modify the default surround variables, click Start and search for 'edit environs variables', or open Organisation properties, Avant-garde system settings and click the Surround Variables button. In this dialog, you tin add or modify User and Arrangement variables. To alter System variables, you need non-restricted admission to your machine (i.e. Administrator rights).

Note

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

The PYTHONPATH variable is used past all versions of Python, and so you lot should not permanently configure information technology 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.5.

Besides using the automatically created start menu entry for the Python interpreter, you might want to start Python in the command prompt. The installer has an option to fix that up for you.

On the start page of the installer, an option labelled "Add Python to PATH" may be selected to have the installer add the install location into the PATH . The location of the Scripts\ folder is also added. This allows y'all to type python to run the interpreter, and pip for the package installer. Thus, you can likewise execute your scripts with control line options, see Command line documentation.

If you don't enable this option at install time, you can always re-run the installer, select Modify, and enable it. Alternatively, you can manually alter the PATH using the directions in Excursus: Setting surround variables. Y'all need to gear up your PATH environment variable to include the directory of your Python installation, delimited past a semicolon from other entries. An instance variable could look like this (assuming the commencement two entries already existed):

                C:\WINDOWS\system32;C:\WINDOWS;C:\Plan Files\Python three.nine              

4.seven. UTF-viii mode¶

New in version 3.7.

Windows still uses legacy encodings for the organisation encoding (the ANSI Code Folio). Python uses it for the default encoding of text files (e.one thousand. locale.getpreferredencoding() ).

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

Y'all can use the Python UTF-eight Mode to change the default text encoding to UTF-viii. You tin enable the Python UTF-viii Mode via the -Ten utf8 command line option, or the PYTHONUTF8=1 surround variable. Run into PYTHONUTF8 for enabling UTF-8 manner, and Excursus: Setting surround variables for how to modify environment variables.

When the Python UTF-8 Mode is enabled, yous tin can notwithstanding use the system encoding (the ANSI Code Folio) via the "mbcs" codec.

Note that adding PYTHONUTF8=1 to the default environment variables will bear on all Python 3.vii+ applications on your system. If you have any Python three.vii+ applications which rely on the legacy organization encoding, it is recommended to set the environment variable temporarily or utilize the -10 utf8 command line option.

Note

Fifty-fifty when UTF-8 way is disabled, Python uses UTF-eight by default on Windows for:

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

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

4.viii. Python Launcher for Windows¶

New in version 3.3.

The Python launcher for Windows is a utility which aids in locating and executing of different Python versions. Information technology allows scripts (or the control-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 most appropriate version of Python. Information technology will prefer per-user installations over system-wide ones, and orders past language version rather than using the most recently installed version.

The launcher was originally specified in PEP 397.

iv.8.1. Getting started¶

4.eight.1.1. From the control-line¶

Inverse in version 3.6.

Organisation-broad installations of Python 3.3 and later will put the launcher on your PATH . The launcher is compatible with all bachelor versions of Python, so information technology does non thing which version is installed. To cheque that the launcher is bachelor, execute the following command in Command Prompt:

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

If you accept multiple versions of Python installed (east.1000., 3.7 and 3.10) you will have noticed that Python three.10 was started - to launch Python 3.7, attempt the command:

If you want the latest version of Python two you have installed, attempt the control:

You should find the latest version of Python 3.ten starts.

If you see the following error, y'all practice non accept the launcher installed:

                  'py' is non recognized as an internal or external control, operable programme or batch file.                

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

The control:

displays the currently installed version(due south) of Python.

4.8.1.2. Virtual environments¶

New in version iii.v.

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

4.8.1.3. From a script¶

Let's create a examination 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 howdy.py lives, execute the command:

You should detect the version number of your latest Python 2.x installation is printed. At present endeavour irresolute the showtime line to be:

Re-executing the control should at present impress the latest Python iii.x data. Every bit with the above command-line examples, you can specify a more explicit version qualifier. Assuming you have Python iii.7 installed, try changing the first line to #! python3.7 and you should find the 3.10 version information printed.

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

iv.8.1.4. From file associations¶

The launcher should have been associated with Python files (i.eastward. .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 volition be used, and therefore you can use the same facilities described higher up to take the script specify the version which should be used.

The key benefit of this is that a single launcher can back up multiple Python versions at the same time depending on the contents of the kickoff line.

iv.8.2. Shebang Lines¶

If the outset 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 unremarkably used on such systems to signal how a script should be executed. This launcher allows the same facilities to be used with Python scripts on Windows and the examples higher up demonstrate their use.

To let 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 utilise. The supported virtual commands are:

  • /usr/bin/env python

  • /usr/bin/python

  • /usr/local/bin/python

  • python

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

The default Python volition be located and used. As many Python scripts written to work on Unix will already have this line, you lot should find these scripts tin be used by the launcher without modification. If y'all are writing a new script on Windows which you hope will be useful on Unix, you should use one of the shebang lines starting with /usr .

Whatever of the higher up virtual commands can be suffixed with an explicit version (either just the major version, or the major and modest version). Furthermore the 32-fleck version can be requested past adding "-32" after the minor version. I.e. /usr/bin/python3.7-32 will request usage of the 32-bit python 3.7.

New in version 3.7: Beginning with python launcher iii.7 it is possible to request 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 class of shebang line has one further special property. Before looking for installed Python interpreters, this form will search the executable PATH for a Python executable. This corresponds to the behaviour of the Unix env programme, which performs a PATH search.

iv.8.three. Arguments in shebang lines¶

The shebang lines tin can too specify additional options to exist passed to the Python interpreter. For example, if you accept a shebang line:

Then Python will be started with the -5 choice

4.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 past calling the Windows function SHGetFolderPath with CSIDL_LOCAL_APPDATA ) and py.ini in the same directory equally the launcher. The same .ini files are used for both the 'console' version of the launcher (i.due east. py.exe) and for the 'windows' version (i.e. pyw.exe).

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

four.8.4.2. Customizing default Python versions¶

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

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

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

If no minor version qualifiers are found, the environment variable PY_PYTHON{major} (where {major} is the current major version qualifier equally determined to a higher place) can exist set up to specify the full version. If no such selection is plant, the launcher volition enumerate the installed Python versions and use the latest small release institute for the major version, which is likely, although not guaranteed, to be the nigh recently installed version in that family.

On 64-chip Windows with both 32-bit and 64-bit implementations of the same (major.minor) Python version installed, the 64-fleck version volition always be preferred. This will be truthful for both 32-bit and 64-flake 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 and so the behavior of the launcher can exist 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-bit version of Python and corresponding launcher was installed concluding). As noted higher up, an optional "-32" or "-64" suffix can be used on a version specifier to change this behaviour.

Examples:

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

  • The command python3.7 will not consult whatever options at all as the versions are fully specified.

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

  • If PY_PYTHON=3.7-32 , the command python volition use the 32-bit implementation of 3.7 whereas the command python3 will use the latest installed Python (PY_PYTHON was not considered at all every bit a major version was specified.)

  • If PY_PYTHON=3 and PY_PYTHON3=3.7 , the commands python and python3 will both use specifically 3.vii

In addition to environment variables, the aforementioned settings tin be configured in the .INI file used past the launcher. The section in the INI file is called [defaults] and the cardinal name will exist the same as the environment variables without the leading PY_ prefix (and note that the primal names in the INI file are case insensitive.) The contents of an surround 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=iii and PY_PYTHON3=3.vii is equivalent to the INI file containing:

                                    [defaults]                                    python                  =                  3                                    python3                  =                  3.7                                  

4.8.5. Diagnostics¶

If an surround variable PYLAUNCH_DEBUG is ready (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, information technology 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.

four.nine. Finding modules¶

Python usually 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 3rd-party modules should be stored in C:\Python\Lib\site-packages\ .

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

When the file exists, all registry and environment variables are ignored, isolated manner is enabled, and site is not 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 not permitted, and arbitrary code cannot be specified.

Note that .pth files (without leading underscore) volition be candy 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 outset, which corresponds to the electric current directory.

  • If the surroundings variable PYTHONPATH exists, as described in Surroundings variables, its entries are added adjacent. 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.).

  • Boosted "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 have semicolon-delimited path strings as their default value will cause each path to be added to sys.path . (Notation that all known installers only use HKLM, so HKCU is typically empty.)

  • If the environment variable PYTHONHOME is set, it is assumed as "Python Abode". Otherwise, the path of the primary Python executable is used to locate a "landmark file" (either Lib\os.py or pythonXY.zip ) to deduce the "Python Home". 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 Home cannot be located, no PYTHONPATH is specified in the environment, and no registry entries tin can exist institute, a default path with relative entries is used (e.g. .\Lib;.\plat-win , etc).

If a pyvenv.cfg file is plant alongside the main executable or in the directory ane level higher up the executable, the following variations apply:

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

The finish consequence of all this is:

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

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

  • If Python can't find its home and there are no registry value (frozen .exe, some very strange installation setup) you get a path with some default, only 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 aslope your executable containing the directories to include. This will ignore paths listed in the registry and environment variables, and also ignore site unless import site is listed.

  • If yous are loading python3.dll or python37.dll in your ain executable, explicitly phone call Py_SetPath() or (at least) Py_SetProgramName() before Py_Initialize() .

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

  • If you cannot use the previous suggestions (for instance, y'all 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 information technology will not be detected inside a ZIP file, but a correctly named ZIP file will exist detected instead.)

These volition ensure that the files in a organization-wide installation volition non take precedence over the copy of the standard library bundled with your application. Otherwise, your users may experience bug using your application. Note that the kickoff suggestion is the all-time, as the others may still be susceptible to non-standard paths in the registry and user site-packages.

Changed in version 3.six:

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

  • Adds pythonXX.cipher equally a potential landmark when straight adjacent to the executable.

Deprecated since version three.six:

Modules specified in the registry nether Modules (not PythonPath ) may exist imported past importlib.machinery.WindowsRegistryFinder . This finder is enabled on Windows in three.6.0 and earlier, but may need to be explicitly added to sys.meta_path in the futurity.

iv.10. Additional modules¶

Even though Python aims to be portable amongst 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.

four.10.ane. 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

  • Effect log

  • Microsoft Foundation Classes (MFC) user interfaces

PythonWin is a sample MFC application shipped with PyWin32. It is an embeddable IDE with a born debugger.

4.10.2. cx_Freeze¶

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

4.11. Compiling Python on Windows¶

If you want to compile CPython yourself, first thing you lot should do is get the source. You can download either the latest release's source or just catch a fresh checkout.

The source tree contains a build solution and projection 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 process.

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

4.12. Other Platforms¶

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

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

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

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