Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 514 – Python registration in the Windows registry

Author:
Steve Dower <steve.dower at python.org>
BDFL-Delegate:
Paul Moore <p.f.moore at gmail.com>
Status:
Active
Type:
Informational
Created:
02-Feb-2016
Post-History:
02-Feb-2016, 01-Mar-2016, 18-Jul-2016
Resolution:
Python-Dev message

Table of Contents

Abstract

This PEP defines a schema for the Python registry key to allow third-partyinstallers to register their installation, and to allow tools and applicationsto detect and correctly display all Python environments on a user’s machine. Noimplementation changes to Python are proposed with this PEP.

Python environments are not required to be registered unless they want to beautomatically discoverable by external tools. As this relates to Windows only,these tools are expected to be predominantly GUI applications. However, consoleapplications may also make use of the registered information. This PEP coversthe information that may be made available, but the actual presentation and useof this information is left to the tool designers.

The schema matches the registry values that have been used by the officialinstaller since at least Python 2.5, and the resolution behaviour matches thebehaviour of the official Python releases. Some backwards compatibility rulesare provided to ensure tools can correctly detect versions of CPython that donot register full information.

Motivation

When installed on Windows, the official Python installer creates a registry keyfor discovery and detection by other applications. This allows tools such asinstallers or IDEs to automatically detect and display a user’s Pythoninstallations. For example, thePEP 397py.exe launcher and editors such asPyCharm and Visual Studio already make use of this information.

Third-party installers, such as those used by distributions, typically createidentical keys for the same purpose. Most tools that use the registry to detectPython installations only inspect the keys used by the official installer. As aresult, third-party installations that wish to be discoverable will overwritethese values, often causing users to “lose” their original Python installation.

By describing a layout for registry keys that allows third-party installationsto register themselves uniquely, as well as providing tool developers guidancefor discovering all available Python installations, these collisions should beprevented. We also take the opportunity to add some well-known metadata so thatmore information can be presented to users.

Definitions

A “registry key” is the equivalent of a file-system path into the registry. Eachkey may contain “subkeys” (keys nested within keys) and “values” (named andtyped attributes attached to a key). These are used on Windows to store settingsin much the same way that directories containing configuration files would work.

HKEY_CURRENT_USER is the root of settings for the currently logged-in user,and this user can generally read and write all settings under this root.

HKEY_LOCAL_MACHINE is the root of settings for all users. Generally, anyuser can read these settings but only administrators can modify them. It istypical for values underHKEY_CURRENT_USER to take precedence over those inHKEY_LOCAL_MACHINE.

On 64-bit Windows,HKEY_LOCAL_MACHINE\Software\Wow6432Node is a special keythat 32-bit processes transparently read and write to rather than accessing theSoftware key directly.

Further documentation regarding registry redirection on Windows is availablefrom the MSDN Library[1].

Structure

We consider there to be a single collection of Python environments on a machine,where the collection may be different for each user of the machine. There arethree potential registry locations where the collection may be stored based onthe installation options of each environment:

HKEY_CURRENT_USER\Software\Python\<Company>\<Tag>HKEY_LOCAL_MACHINE\Software\Python\<Company>\<Tag>HKEY_LOCAL_MACHINE\Software\Wow6432Node\Python\<Company>\<Tag>

Official Python releases usePythonCore for Company, and the value ofsys.winver for Tag. The CompanyPyLauncher is reserved. Other registeredenvironments may use any values for Company and Tag. Recommendations are madelater in this document.

Company-Tag pairs are case-insensitive, and uniquely identify each environment.Depending on the purpose and intended use of a tool, there are two suggestedapproaches for resolving conflicts between Company-Tag pairs.

Tools that list every installed environment may choose to include thoseeven where the Company-Tag pairs match. They should ensure users can easilyidentify whether the registration was per-user or per-machine, and whichregistration has the higher priority.

Tools that aim to select a single installed environment from all registeredenvironments based on the Company-Tag pair, such as thepy.exe launcher,should always select the environment registered inHKEY_CURRENT_USER whenthan the matching one inHKEY_LOCAL_MACHINE.

Conflicts betweenHKEY_LOCAL_MACHINE\Software\Python andHKEY_LOCAL_MACHINE\Software\Wow6432Node\Python should only occur when both64-bit and 32-bit versions of an interpreter have the same Tag. In this case,the tool should select whichever is more appropriate for its use.

If a tool is able to determine from the provided information (or lack thereof)that it cannot use a registered environment, there is no obligation to presentit to users.

Except as discussed in the section on backwards compatibility, Company and Tagvalues are considered opaque to tools, and no information about the interpretershould be inferred from the text. However, some tools may display the Companyand Tag values to users, so ideally the Tag will be able to help users identifythe associated environment.

Python environments are not required to register themselves unless they want tobe automatically discoverable by external tools.

Backwards Compatibility

Python 3.4 and earlier did not distinguish between 32-bit and 64-bit builds insys.winver. As a result, it is not possible to have valid side-by-sideinstallations of both 32-bit and 64-bit interpreters under this scheme since itwould result in duplicate Tags.

To ensure backwards compatibility, applications should treat environments listedunder the following two registry keys as distinct, even when the Tag matches:

HKEY_LOCAL_MACHINE\Software\Python\PythonCore\<Tag>HKEY_LOCAL_MACHINE\Software\Wow6432Node\Python\PythonCore\<Tag>

Environments listed underHKEY_CURRENT_USER may be treated as distinct fromboth of the above keys, potentially resulting in three environments discoveredusing the same Tag. Alternatively, a tool may determine whether the per-userenvironment is 64-bit or 32-bit and give it priority over the per-machineenvironment, resulting in a maximum of two discovered environments.

It is not possible to detect side-by-side installations of both 64-bit and32-bit versions of Python prior to 3.5 when they have been installed for thecurrent user. Python 3.5 and later always uses different Tags for 64-bit and32-bit versions.

The following section describe user-visible information that may be registered.For Python 3.5 and earlier, none of this information is available, butalternative defaults are specified for thePythonCore key.

Environments registered under other Company names have no backward compatibilityrequirements and must use distinct Tags to support side-by-side installations.Tools consuming these registrations are not required to disambiguate tags otherthan by preferring the user’s setting.

Company

The Company part of the key is intended to group related environments and toensure that Tags are namespaced appropriately. The key name should bealphanumeric without spaces and likely to be unique. For example, a trademarkedname (preferred), a hostname, or as a last resort, a UUID would be appropriate:

HKEY_CURRENT_USER\Software\Python\ExampleCorpHKEY_CURRENT_USER\Software\Python\www.example.comHKEY_CURRENT_USER\Software\Python\6C465E66-5A8C-4942-9E6A-D29159480C60

The company namePyLauncher is reserved for thePEP 397 launcher(py.exe). It does not follow this convention and should be ignored by tools.

If a string value namedDisplayName exists, it should be used to identifythe environment manufacturer/developer/distributor to users. Otherwise, the nameof the key should be used. (ForPythonCore, the default display name is“Python Software Foundation”.)

If a string value namedSupportUrl exists, it may be displayed or otherwiseused to direct users to a web site related to the environment. (ForPythonCore, the default support URL is “http://www.python.org/”.)

A complete example may look like:

HKEY_CURRENT_USER\Software\Python\ExampleCorp(Default)=(valuenotset)DisplayName="Example Corp"SupportUrl="http://www.example.com"

Tag

The Tag part of the key is intended to uniquely identify an environment withinthose provided by a single company. The key name should be alphanumeric withoutspaces and stable across installations. For example, the Python languageversion, a UUID or a partial/complete hash would be appropriate, while a Tagbased on the install directory or some aspect of the current machine may not.For example:

HKEY_CURRENT_USER\Software\Python\ExampleCorp\examplepyHKEY_CURRENT_USER\Software\Python\ExampleCorp\3.6HKEY_CURRENT_USER\Software\Python\ExampleCorp\6C465E66

It is expected that some tools will require users to type the Tag into a commandline, and that the Company may be optional provided the Tag is unique across allPython installations. Short, human-readable and easy to type Tags arerecommended, and if possible, select a value likely to be unique across allother Companies.

If a string value namedDisplayName exists, it should be used to identifythe environment to users. Otherwise, the name of the key should be used. (ForPythonCore, the default is “Python “ followed by the Tag.)

If a string value namedSupportUrl exists, it may be displayed or otherwiseused to direct users to a web site related to the environment. (ForPythonCore, the default is “http://www.python.org/”.)

If a string value namedVersion exists, it should be used to identify theversion of the environment. This is independent from the version of Pythonimplemented by the environment. (ForPythonCore, the default is the firstthree characters of the Tag.)

If a string value namedSysVersion exists, it must be inx.y orx.y.z format matching the version returned bysys.version_info in theinterpreter. If omitted, the Python version is unknown. (ForPythonCore,the default is the first three characters of the Tag.)

If a string value namedSysArchitecture exists, it must match the firstelement of the tuple returned byplatform.architecture(). Typically, thiswill be “32bit” or “64bit”. If omitted, the architecture is unknown. (ForPythonCore, the architecture is “32bit” when registered underHKEY_LOCAL_MACHINE\Software\Wow6432Node\Pythonor anywhere on a 32-bitoperating system, “64bit” when registered underHKEY_LOCAL_MACHINE\Software\Python on a 64-bit machine, and unknown whenregistered underHKEY_CURRENT_USER.)

Note that each of these values is recommended, but optional. OmittingSysVersion orSysArchitecture may prevent some tools from correctlysupporting the environment. A complete example may look like this:

HKEY_CURRENT_USER\Software\Python\ExampleCorp\examplepy(Default)=(valuenotset)DisplayName="Example Py Distro 3"SupportUrl="http://www.example.com/distro-3"Version="3.0.12345.0"SysVersion="3.6.0"SysArchitecture="64bit"

InstallPath

Beneath the environment key, anInstallPath key must be created. This key isalways namedInstallPath, and the default value must matchsys.prefix:

HKEY_CURRENT_USER\Software\Python\ExampleCorp\3.6\InstallPath(Default)="C:\ExampleCorpPy36"

If a string value namedExecutablePath exists, it must be the full path tothepython.exe (or equivalent) executable. If omitted, the environment isnot executable. (ForPythonCore, the default is thepython.exe file inthe directory referenced by the(Default) value.)

If a string value namedExecutableArguments exists, tools should use thevalue as the first arguments when executingExecutablePath. Tools may addother arguments following these, and will reasonably expect standard Pythoncommand line options to be available.

If a string value namedWindowedExecutablePath exists, it must be a path tothepythonw.exe (or equivalent) executable. If omitted, the default is thevalue ofExecutablePath, and if that is omitted the environment is notexecutable. (ForPythonCore, the default is thepythonw.exe file in thedirectory referenced by the(Default) value.)

If a string value namedWindowedExecutableArguments exists, tools should usethe value as the first arguments when executingWindowedExecutablePath.Tools may add other arguments following these, and will reasonably expectstandard Python command line options to be available.

A complete example may look like:

HKEY_CURRENT_USER\Software\Python\ExampleCorp\examplepy\InstallPath(Default)="C:\ExampleDistro30"ExecutablePath="C:\ExampleDistro30\ex_python.exe"ExecutableArguments="--arg1"WindowedExecutablePath="C:\ExampleDistro30\ex_pythonw.exe"WindowedExecutableArguments="--arg1"

Help

Beneath the environment key, aHelp key may be created. This key is alwaysnamedHelp if present and has no default value.

Each subkey ofHelp specifies a documentation file, tool, or URL associatedwith the environment. The subkey may have any name, and the default value is astring appropriate for passing toos.startfile or equivalent.

If a string value namedDisplayName exists, it should be used to identifythe help file to users. Otherwise, the key name should be used.

A complete example may look like:

HKEY_CURRENT_USER\Software\Python\ExampleCorp\6C465E66\HelpPython\(Default)="C:\ExampleDistro30\python36.chm"DisplayName="Python Documentation"Extras\(Default)="http://www.example.com/tutorial"DisplayName="Example Distro Online Tutorial"

Other Keys

All other subkeys under a Company-Tag pair are available for private use.

Official CPython releases have traditionally used certain keys in this space todetermine the location of the Python standard library and other installedmodules. This behaviour is retained primarily for backward compatibility.However, as the code that reads these values is embedded into the interpreter,third-party distributions may be affected by values written intoPythonCoreif using an unmodified interpreter.

Sample Code

This sample code enumerates the registry and displays the available Company-Tagpairs that could be used to launch an environment and the target executable. Itonly shows the most-preferred target for the tag. Backwards-compatible handlingofPythonCore is omitted but shown in a later example:

# Display most-preferred environments.# Assumes a 64-bit operating system# Does not correctly handle PythonCore compatibilityimportwinregdefenum_keys(key):i=0whileTrue:try:yieldwinreg.EnumKey(key,i)exceptOSError:breaki+=1defget_value(key,value_name):try:returnwinreg.QueryValue(key,value_name)exceptFileNotFoundError:returnNoneseen=set()forhive,key,flagsin[(winreg.HKEY_CURRENT_USER,r'Software\Python',0),(winreg.HKEY_LOCAL_MACHINE,r'Software\Python',winreg.KEY_WOW64_64KEY),(winreg.HKEY_LOCAL_MACHINE,r'Software\Python',winreg.KEY_WOW64_32KEY),]:withwinreg.OpenKeyEx(hive,key,access=winreg.KEY_READ|flags)asroot_key:forcompanyinenum_keys(root_key):ifcompany=='PyLauncher':continuewithwinreg.OpenKey(root_key,company)ascompany_key:fortaginenum_keys(company_key):if(company,tag)inseen:ifcompany=='PythonCore':# TODO: Backwards compatibility handlingpasscontinueseen.add((company,tag))try:withwinreg.OpenKey(company_key,tag+r'\InstallPath')asip_key:exec_path=get_value(ip_key,'ExecutablePath')exec_args=get_value(ip_key,'ExecutableArguments')ifcompany=='PythonCore'andnotexec_path:# TODO: Backwards compatibility handlingpassexceptOSError:exec_path,exec_args=None,Noneifexec_path:print('{}\\{} -{}{}'.format(company,tag,exec_path,exec_argsor''))else:print('{}\\{} - (not executable)'.format(company,tag))

This example only scansPythonCore entries for the current user. Where datais missing, the defaults as described earlier in the PEP are substituted. Notethat these defaults are only for use underPythonCore; other registrationsdo not have any default values:

# Only lists per-user PythonCore registrations# Uses fallback values as described in PEP 514importosimportwinregdefenum_keys(key):i=0whileTrue:try:yieldwinreg.EnumKey(key,i)exceptOSError:breaki+=1defget_value(key,value_name):try:returnwinreg.QueryValue(key,value_name)exceptFileNotFoundError:returnNonewithwinreg.OpenKey(winreg.HKEY_CURRENT_USER,r"Software\Python\PythonCore")ascompany_key:print('Company:',get_value(company_key,'DisplayName')or'Python Software Foundation')print('Support:',get_value(company_key,'SupportUrl')or'http://www.python.org/')print()fortaginenum_keys(company_key):withwinreg.OpenKey(company_key,tag)astag_key:print('PythonCore\\'+tag)print('Name:',get_value(tag_key,'DisplayName')or('Python '+tag))print('Support:',get_value(tag_key,'SupportUrl')or'http://www.python.org/')print('Version:',get_value(tag_key,'Version')ortag[:3])print('SysVersion:',get_value(tag_key,'SysVersion')ortag[:3])# Architecture is unknown because we are in HKCU# Tools may use alternate approaches to determine architecture when# the registration does not specify it.print('SysArchitecture:',get_value(tag_key,'SysArchitecture')or'(unknown)')try:ip_key=winreg.OpenKey(company_key,tag+'\\InstallPath')exceptFileNotFoundError:passelse:withip_key:ip=get_value(ip_key,None)exe=get_value(ip_key,'ExecutablePath')oros.path.join(ip,'python.exe')exew=get_value(ip_key,'WindowedExecutablePath')oros.path.join(ip,'python.exe')print('InstallPath:',ip)print('ExecutablePath:',exe)print('WindowedExecutablePath:',exew)print()

This example shows a subset of the registration that will be created by ajust-for-me install of 64-bit Python 3.6.0. Other keys may also be created:

HKEY_CURRENT_USER\Software\Python\PythonCore(Default)=(valuenotset)DisplayName="Python Software Foundation"SupportUrl="http://www.python.org/"HKEY_CURRENT_USER\Software\Python\PythonCore\3.6(Default)=(valuenotset)DisplayName="Python 3.6 (64-bit)"SupportUrl="http://www.python.org/"Version="3.6.0"SysVersion="3.6"SysArchitecture="64bit"HKEY_CURRENT_USER\Software\Python\PythonCore\3.6\Help\MainPythonDocumentation(Default)="C:\Users\Me\AppData\Local\Programs\Python\Python36\Doc\python360.chm"DisplayName="Python 3.6.0 Documentation"HKEY_CURRENT_USER\Software\Python\PythonCore\3.6\InstallPath(Default)="C:\Users\Me\AppData\Local\Programs\Python\Python36\"ExecutablePath="C:\Users\Me\AppData\Local\Programs\Python\Python36\python.exe"WindowedExecutablePath="C:\Users\Me\AppData\Local\Programs\Python\Python36\pythonw.exe"

References

[1]
Registry Redirector (Windows)(https://msdn.microsoft.com/en-us/library/windows/desktop/aa384232.aspx)

Copyright

This document has been placed in the public domain.


Source:https://github.com/python/peps/blob/main/peps/pep-0514.rst

Last modified:2025-02-01 08:59:27 GMT


[8]ページ先頭

©2009-2025 Movatter.jp