0% ont trouvé ce document utile (0 vote)
5 vues44 pages

Utilisation de Python Sous Windows

Ce document fournit un aperçu de l'utilisation de Python sous Windows, en soulignant les différences par rapport aux systèmes Unix et en expliquant comment installer et gérer Python via le gestionnaire d'installation. Il aborde également la création d'environnements virtuels pour l'isolation des projets et les commandes de base pour exécuter et gérer les versions de Python. Enfin, il traite des options de configuration, de désinstallation et d'installation hors ligne des runtimes Python.

Transféré par

papa momar cisse
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats DOC, PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
5 vues44 pages

Utilisation de Python Sous Windows

Ce document fournit un aperçu de l'utilisation de Python sous Windows, en soulignant les différences par rapport aux systèmes Unix et en expliquant comment installer et gérer Python via le gestionnaire d'installation. Il aborde également la création d'environnements virtuels pour l'isolation des projets et les commandes de base pour exécuter et gérer les versions de Python. Enfin, il traite des options de configuration, de désinstallation et d'installation hors ligne des runtimes Python.

Transféré par

papa momar cisse
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats DOC, PDF, TXT ou lisez en ligne sur Scribd

Utilisation de Python sous Windows

Ce document vise à donner un aperçu des comportements spécifiques à


Windows que vous devriez À savoir quand on utilise Python sous Microsoft
Windows.

Contrairement à la plupart des systèmes et services Unix, Windows


n’inclut pas de système prise en charge de l’installation de Python. À la
place, Python peut être obtenu à partir d’un nombre de distributeurs, y
compris directement de l’équipe CPython. Chaque Python La distribution
aura ses propres avantages et inconvénients, cependant, la cohérence
avec D’autres outils que vous utilisez sont généralement un avantage
intéressant. Avant de s’engager Pour le processus décrit ici, nous
recommandons d’examiner vos outils existants pour vois s’ils peuvent
fournir directement Python.

Pour obtenir Python auprès de l’équipe CPython, utilisez le gestionnaire


d’installation de Python. Exactement est un outil autonome qui rend
Python disponible en commandes globales sur votre Machine Windows,
s’intègre au système et prend en charge les mises à jour au fil du temps.
Toi peut télécharger le gestionnaire d’installation Python
depuis [Link]/downloads ou via l’application du Microsoft Store.

Une fois le gestionnaire d’installation Python installé, la commande globale


peut être utilisée depuis n’importe quel terminal pour lancer la dernière
version actuelle de Python. Cette version peut évoluer au fil du temps au
fur et à mesure que vous ajoutez ou retirez différentes versions et la
commande indiquera lesquelles sont en cours. pythonpy list

En général, nous recommandons de créer un environnement virtuel pour


chaque projet et de l’exécuter dans votre terminal pour l’utiliser. Cela
assure l’isolation entre les projets, la cohérence dans le temps, et garantit
que des commandes supplémentaires ajoutées par des packages sont
également disponibles dans votre session. Créez un environnement virtuel
en utilisant .<env>\Scripts\Activatepython -m venv <env path>

Si les commandes ou ne semblent pas fonctionner, veuillez consulter la


section Dépannage ci-dessous. Il y en a parfois des étapes manuelles
supplémentaires nécessaires pour configurer votre PC. pythonpy

En plus de l’utilisation du gestionnaire d’installation Python, Python peut


également être obtenu sous la forme Colis NuGet. Consultez les forfaits
The [Link] ci-dessous pour plus d’informations à ce sujet Des colis.

Les distributions embarquables sont des paquets minimals de Python


adaptés à l’intégration vers des applications plus larges. Ils peuvent être
installés en utilisant l’installation Python Manager. Voir le package
intégrable ci-dessous pour plus d’informations à ce sujet Des colis.
4.1. Gestionnaire d’installation Python
4.1.1. Installation
Le gestionnaire d’installation Python peut être installé depuis l’application Microsoft Store ou
téléchargé et installé depuis [Link]/downloads. Les deux versions sont identique.

Pour installer via le Store, il suffit de cliquer sur « Installer ». Après son achèvement, Ouvre
un terminal et tape pour [Link]

Pour installer le fichier téléchargé depuis [Link], double-cliquez et sélectionnez «


Installer », ou exécuter sous Windows [Link]-AppxPackage <path to MSIX>

Après installation, les commandes , , et doivent être disponible. Si vous avez déjà des
installations de Python, ou si vous avez modifié votre variable, vous devrez peut-être les
retirer ou annuler la modifications. Consultez le service de dépannage pour plus d’aide à la
réparation Commandes non [Link]

Lorsque vous installez un runtime pour la première fois, on vous demandera probablement
d’ajouter un dossier à votre . C’est optionnel, si vous préférez utiliser la commande, mais cela
s’adresse à ceux qui préfèrent toute la gamme d’alias (par exemple comme ) pour être
disponible. Le répertoire sera par défaut, mais pourra être personnalisé par un Administrateur.
Cliquez sur Démarrer et cherchez « Modifier les variables d’environnement pour votre
compte » pour la page des paramètres système afin d’ajouter le
[Link]%LocalAppData%\Python\bin

Chaque runtime Python que vous installez aura son propre répertoire pour les scripts. Ceux-ci
Il faut aussi les ajouter si vous voulez les [Link]

Le gestionnaire d’installation Python sera automatiquement mis à jour aux nouvelles versions.
Exactement n’affecte aucune installation des runtimes Python. Désinstallation de l’installation
de Python gestionnaire ne désinstalle aucun runtime Python.

Si vous ne pouvez pas installer un MSIX dans votre contexte, par exemple, vous pouvez
Utilisation de logiciels de déploiement automatisé qui ne le prennent pas en charge, ou qui
ciblent Windows Server 2019, veuillez consulter l’installation avancée ci-dessous pour en
savoir plus informations.

4.1.2. Utilisation de base


La commande recommandée pour lancer Python est , qui sera soit lancer la version demandée
par le script en cours de lancement, un Virtual actif environnement, ou la version installée par
défaut, qui sera la dernière version stable Libérez sauf indication contraire. Si aucune version
n’est spécifiquement demandée et aucun runtime n’est installé, la dernière version actuelle
sera installée [Link]

Pour tous les scénarios impliquant plusieurs versions d’exécution, la commande


recommandée est . Cela peut être utilisé n’importe où à la place de l’ancien lanceur ou de
celui-ci. Par défaut, correspond au comportement de , mais Permet également aux options de
ligne de commande de sélectionner une version spécifique ainsi que sous-commandes pour
gérer les installations. Celles-ci sont détaillées [Link]

Puisque la commande peut déjà être prise par la version précédente, là est aussi un ordre sans
équivoque. Installations scriptées qui sont Si vous souhaitez utiliser le gestionnaire
d’installation Python, il faut envisager d’utiliser , en raison ainsi que le risque de conflit avec
les installations existantes diminue. Le seul La différence entre les deux commandes est que
lorsqu’elles s’exécutent sans aucun argument : lance votre interpréteur par défaut, tandis que
s’affiche help ( fournit un comportement équivalent
à ).pypymanagerpymanagerpypymanagerpymanager exec ...py ...

Chacune de ces commandes possède également une version fenêtrée qui évite de créer un
Fenêtre de la console. Ce sont , et . Une commande est également incluse qui imite la
commande. Il est destiné à détecter des usages accidentels de la commande POSIX typique
sur Windows, mais ce n’est pas intentionnel à être largement utilisé ou
recommandé.pywpythonwpymanagerwpython3python

Pour lancer votre runtime par défaut, exécutez ou avec les arguments que vous souhaite être
transmis à l’exécution (comme les fichiers script ou le module à lancer) :pythonpy

$> py
...
$> python [Link]
...
$> py -m this
...

L’exécution par défaut peut être remplacée par la variable d’environnement ou un fichier de
configuration. Voir Configuration pour Informations sur les paramètres de configuration.

Pour lancer un runtime spécifique, la commande accepte une option. Cette option doit être
spécifiée avant toute autre. L’étagère fait partie ou la totalité de la identifiant pour
l’exécution ; pour ceux de l’équipe CPython, il semble que le Éventuellement, avec la
plateforme. Pour la compatibilité, les peuvent être Omis dans les cas où le tag fait référence à
une version officielle et commence par .py-V:<TAG>V:3

$> py -V:3.14 ...


$> py -V:3-arm64 ...

Les temps d’exécution d’autres distributeurs peuvent exiger que la société soit incluse comme
eh bien. Celle-ci doit être séparée de l’étiquette par une barre oblique, et peut être un préfixe.
Spécifier l’entreprise est optionnel lorsque c’est , et spécifier le Le tag est optionnel (mais pas
la barre oblique) lorsque vous voulez la dernière version d’un Entreprise
spé[Link]

$> py -V:Distributor\1.0 ...


$> py -V:distrib/ ...
If no version is specified, but a script file is passed, the script will be inspected for a shebang
line. This is a special format for the first line in a file that allows overriding the command.
See Shebang lines for more information. When there is no shebang line, or it cannot be
resolved, the script will be launched with the default runtime.

If you are running in an active virtual environment, have not requested a particular version,
and there is no shebang line, the default runtime will be that virtual environment. In this
scenario, the command was likely already overridden and none of these checks occurred.
However, this behaviour ensures that the command can be used [Link]

When no runtimes are installed, any launch command will try to install the requested version
and launch it. However, after any version is installed, only the and commands will install if
the requested version is absent. Other forms of commands will display an error and direct you
to use [Link] exec ...pymanager exec ...py install

4.1.3. Command help


The command will display the full list of supported commands, along with their options. Any
command may be passed the option to display its help, or its name passed to .py help-?
py help

$> py help
$> py help install
$> py install /?

All commands support some common options, which will be shown by . These options must
be specified after any subcommand. Specifying or will increase the amount of output shown,
and will increase it further for debugging purposes. Passing or will reduce output, and will
reduce it [Link] help-v--verbose-vv-q--quiet-qq

The option allows specifying a configuration file to override multiple settings at once.
See Configuration below for more information about these files.--config=<PATH>

4.1.4. Listing runtimes


$> py list [-f=|--format=<FMT>] [-1|--one] [--online|-s=|--
source=<URL>] [<TAG>...]

The list of installed runtimes can be seen using . A filter may be added in the form of one or
more tags (with or without company specifier), and each may include a , , or prefix to restrict
to a [Link] list<<=>=>

A range of formats are supported, and can be passed as the or option. Formats include (a user
friendly table view), (comma-separated table), (a single JSON blob), (one JSON blob per
result), (just the executable path), (just the prefix path).--format=<FMT>-
f <FMT>tablecsvjsonjsonlexeprefix

The or option only displays a single result. If the default runtime is included, it will be the
one. Otherwise, the “best” result is shown (“best” is deliberately vaguely defined, but will
usually be the most recent version). The result shown by will match the runtime that would be
launched by .--one-1py list --one <TAG>py -V:<TAG>

The option excludes results that were not installed by the Python install manager. This is
useful when determining which runtimes may be updated or uninstalled through
the command.--only-managedpy

The option is short for passing with the default source. Passing either of these options will
search the online index for runtimes that can be installed. The result shown by will match the
runtime that would be installed by .--online--source=<URL>py list --
online --one <TAG>py install <TAG>

$> py list --online 3.14

For compatibility with the old launcher, the , , and commands (e.g. ) are retained. They do not
allow additional options, and will produce legacy formatted output.--list--list-
paths-0-0ppy -0p

4.1.5. Installing runtimes


$> py install [-s=|--source=<URL>] [-f|--force] [-u|--update] [--
dry-run] [<TAG>...]

New runtime versions may be added using . One or more tags may be specified, and the
special tag may be used to select the default. Ranges are not supported for
[Link] installdefault

The option allows overriding the online index that is used to obtain runtimes. This may be
used with an offline index, as shown in Offline installs.--source=<URL>

Passing will ignore any cached files and remove any existing install to replace it with the
specified one.--force

Passing will replace existing installs if the new version is newer. Otherwise, they will be left.
If no tags are provided with , all installs managed by the Python install manager will be
updated if newer versions are available. Updates will remove any modifications made to the
install, including globally installed packages, but virtual environments will continue to
work.--update--update

Passing will generate output and logs, but will not modify any installs.--dry-run

Passing will update all registrations for installed runtimes. This will recreate Start menu
shortcuts, registry keys, and global aliases (such as or for any installed scripts). These are
automatically refreshed on installation of any runtime, but may need to be manually refreshed
after installing packages.--[Link]

In addition to the above options, the option will extract the runtime to the specified directory
instead of doing a normal install. This is useful for embedding runtimes into larger
applications. Unlike a normal install, will not be aware of the extracted runtime, and no Start
menu or other shortcuts will be created. To launch the runtime, directly execute the main
executable (typically ) in the target directory.--[Link]

$> py install ... [-t=|--target=<PATH>] <TAG>

The command will install the requested runtime if it is not already present. This is controlled
by the configuration (PYTHON_MANAGER_AUTOMATIC_INSTALL), and is enabled by
default. If no runtimes are available at all, all launch commands will do an automatic install if
the configuration setting allows. This is to ensure a good experience for new users, but should
not generally be relied on rather than using the command or explicit install
[Link] execautomatic_installpy exec

4.1.6. Offline installs


To perform offline installs of Python, you will need to first create an offline index on a
machine that has network access.

$> py install --download=<PATH> ... <TAG>...

The option will download the packages for the listed tags and create a directory containing
them and an file suitable for later installation. This entire directory can be moved to the
offline machine and used to install one or more of the bundled runtimes:--
download=<PATH>[Link]

$> py install --source="<PATH>\[Link]" <TAG>...

The Python install manager can be installed by downloading its installer and moving it to
another machine before installing.

Sinon, les fichiers ZIP dans un répertoire d’index hors ligne peuvent simplement être transféré
sur une autre machine et extrait. Cela n’enregistrera pas l’installation de quelque manière que
ce soit, il doit donc être lancé en référant directement les exécutables dans le répertoire extrait,
mais c’est parfois une approche préférable dans certains cas où l’installation du gestionnaire
d’installation Python n’est ni possible ni pratique.

De cette manière, les temps d’exécution Python peuvent être installés et gérés sur une
machine sans L’accès à Internet.

4.1.7. Désinstallation des runtimes


$> py uninstall [-y|--yes] <TAG>...

Les temps d’exécution peuvent être supprimés à l’aide de la commande. Un ou plusieurs tags
Il faut préciser. Les champs de tir ne sont pas pris en charge [Link] uninstall

L’option contourne l’invite de confirmation avant de désinstaller.--yes


Au lieu de passer les tags individuellement, l’option peut être spécifiée. Cela supprimera tous
les temps d’exécution gérés par le gestionnaire d’installation Python, y compris nettoyer le
menu Démarrer, le registre et tous les caches de téléchargement. Des temps d’exécution qui
n’ont pas été installés par le gestionnaire d’installation Python ne seront pas affectés, et
Aucun des fichiers de configuration créés manuellement.--purge

$> py uninstall [-y|--yes] --purge

Le gestionnaire d’installation Python peut être désinstallé via la fonction « Installé » de


Windows Page de paramètres des applications. Cela ne supprime aucun temps d’exécution, et
ils le resteront utilisable, bien que les commandes AND globales soient supprimées.
Réinstaller le gestionnaire d’installation Python vous permettra de gérer ces environnements
d’exécution encore. Pour nettoyer complètement tous les runtimes Python, utilisez les
précédents désinstallation du gestionnaire d’installation [Link]--purge

4.1.8. Configuration
Le gestionnaire d’installation Python est configuré avec une hiérarchie de fichiers de
configuration, variables d’environnement, options en ligne de commande et paramètres du
registre. En général, Les fichiers de configuration ont la capacité de tout configurer, y compris
le emplacement des autres fichiers de configuration, tandis que les paramètres du registre sont
uniquement administrateur et qui supprimera les fichiers de configuration. Options en ligne de
commande Annulez tous les autres réglages, mais toutes les options ne sont pas disponibles.

Cette section décritra les paramètres par défaut, mais sachez que modifié ou Les installations
surchargées peuvent résoudre les paramètres différemment.

Un fichier de configuration global peut être configuré par un administrateur, et serait Lisez
d’abord. Le fichier de configuration utilisateur est stocké à (notez que cet emplacement est
sous , non ) et est lu ensuite, Écraser tous les paramètres des fichiers antérieurs. Un fichier de
configuration supplémentaire peut être spécifié comme la variable d’environnement ou
l’option en ligne de commande (mais pas les deux). Ces emplacements peuvent être modifiés
par les options de personnalisation administrative listées Plus tard.%AppData%\Python\
pymanager.jsonRoamingLocalPYTHON_MANAGER_CONFIG--config

Les paramètres suivants sont considérés comme susceptibles d’être modifiés dans Utilisation
normale. Les sections ultérieures listent celles destinées à l’administration Personnalisation.

Options de configuration standard

Clé de configuration Variable d’environnement Description


default_tag PYTHON_MANAGER_DEFAUL La version par défaut
T préférée pour lancer ou
installer. Par défaut, cela
est interprété comme la
version la plus récente
non pré-release de
Clé de configuration Variable d’environnement Description
l’équipe CPython.
La plateforme par défaut
préférée pour lancer ou
installer. Cela est traité
comme un suffixe de
l’etiqueta spécifiée, de
sorte que l’on préférerait
default_platfo PYTHON_MANAGER_DEFAU une installation si elle
rm LT_PLATFORM existe (et est ), mais je
l’utiliserai si aucune
installation taguée
n’[Link] -
V:3.143.14-
64default_platfor
m-643.14
L’endroit où les fichiers
logs_dir PYTHON_MANAGER_LOGS journaux sont écrits. Par
défaut, .%TEMP%
C’est vrai pour
permettre des
installations
automatiques lors
du lancement (ou
quand aucun temps
d’exécution n’est
automatic_inst PYTHON_MANAGER_AUT encore installé).
all OMATIC_INSTALL Les autres
commandes ne
s’installent pas
automatiquement,
quoi qu’il en soit
Cadre. Par défaut,
c’est
[Link] execpy
include_un PYTHON_MANAGER_IN C’est vrai pour
managed CLUDE_UNMANAGED permettre d’afficher
et de lancer des
environnements
d’exécution qui
n’étaient pas
installés par le
gestionnaire
d’installation
Python, ou faux
pour les exclure.
Par défaut, c’est
Clé de configuration Variable d’environnement Description
vrai.
Vrai pour permettre
des shebangs dans
les fichiers pour
shebang_ca PYTHON_MANAGER_SH lancer d’autres
n_run_anyt EBANG_CAN_RUN_ANY applications que
hing THING Python, ou faux
pour l’éviter. Par
défaut, c’est
vrai..py
Set the default level
of output (0-50).
By default, 20.
Lower values
produce more
output. The
PYMANAGER_VERBOSE, environment
log_level
PYMANAGER_DEBUG variables are
boolean, and may
produce additional
output during
startup that is later
suppressed by other
configuration.
True to confirm
certain actions
before taking them
PYTHON_MANAGER_CO
confirm (such as uninstall),
NFIRM
or false to skip the
confirmation. By
default, true.
Override the index
[Link] PYTHON_MANAGER_SO
feed to obtain new
urce URCE_URL
installs from.
[Link] (none) True to generate
able_entry global commands
points for installed
packages (such as ).
These are defined
by the packages
themselves. If set to
false, only the
Python interpreter
has global
commands created.
Clé de configuration Variable d’environnement Description
By default, true.
You should
run after changing
this
[Link]
y install --
refresh
Specify the default
format used by
[Link] PYTHON_MANAGER_LI
the command. By
t ST_FORMAT
default, .py list
table
Specify the root
directory that
runtimes will be
installed into. If
you change this
install_di
(none) setting, previously
r
installed runtimes
will not be usable
unless you move
them to the new
location.
Specify the
directory where
global commands
(such as and ) are
stored. This
directory should be
global_dir (none) added to your to
make the
commands
available from your
terminal.python3
.[Link]
ePATH
Specify the
directory where
downloaded files
are stored. This
download_d
(none) directory is a
ir
temporary cache,
and can be cleaned
up from time to
time.
Dotted names should be nested inside JSON objects, for example, would be specified
as .[Link]{"list": {"format": "table"}}

4.1.9. Shebang lines


If the first line of a script file starts with , it is known as a “shebang” line. Linux and other
Unix like operating systems have native support for such lines and they are commonly used
on such systems to indicate how a script should be executed. The and commands allow the
same facilities to be used with Python scripts on Windows.#!pythonpy

To allow shebang lines in Python scripts to be portable between Unix and Windows, a
number of ‘virtual’ commands are supported to specify which interpreter to use. The
supported virtual commands are:

 /usr/bin/env <ALIAS>
 /usr/bin/env -S <ALIAS>
 /usr/bin/<ALIAS>
 /usr/local/bin/<ALIAS>
 <ALIAS>

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

#! /usr/bin/python

The default Python or an active virtual environment will be located and used. As many
Python scripts written to work on Unix will already have this line, you should find these
scripts can be used by the launcher without modification. If you 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

Any of the above virtual commands can have replaced by an alias from an installed runtime.
That is, any command generated in the global aliases directory (which you may have added to
your environment variable) can be used in a shebang, even if it is not on your . This allows the
use of shebangs like to select a particular
runtime.<ALIAS>PATHPATH/usr/bin/python3.12

If no runtimes are installed, or if automatic installation is enabled, the requested runtime will
be installed if necessary. See Configuration for information about configuration settings.

The form of shebang line will also search the environment variable for unrecognized
commands. This corresponds to the behaviour of the Unix program, which performs the same
search, but prefers launching known Python commands. A warning may be displayed when
searching for arbitrary executables, and this search may be disabled by the configuration
option./usr/bin/envPATHenvshebang_can_run_anything

Shebang lines that do not match any of patterns are treated as Windows executable paths that
are absolute or relative to the directory containing the script file. This is a convenience for
Windows-only scripts, such as those generated by an installer, since the behavior is not
compatible with Unix-style shells. These paths may be quoted, and may include multiple
arguments, after which the path to the script and any additional arguments will be appended.
This functionality may be disabled by the configuration
option.shebang_can_run_anything

Note

The behaviour of shebangs in the Python install manager is subtly different from the
previous [Link] launcher, and the old configuration options no longer apply. If you are
specifically reliant on the old behaviour or configuration, we recommend installing the legacy
launcher. The legacy launcher’s py command will override PyManager’s one by default, and
you will need to use pymanager commands for installing and uninstalling.

4.1.10. Advanced installation


For situations where an MSIX cannot be installed, such as some older administrative
distribution platforms, there is an MSI available from the [Link] downloads page. This
MSI has no user interface, and can only perform per-machine installs to its default location in
Program Files. It will attempt to modify the system environment variable to include this
install location, but be sure to validate this on your [Link]

Note

Windows Server 2019 is the only version of Windows that CPython supports that does not
support MSIX. For Windows Server 2019, you should use the MSI.

Be aware that the MSI package does not bundle any runtimes, and so is not suitable for
installs into offline environments without also creating an offline install index. See Offline
installs and Administrative configuration for information on handling these scenarios.

Runtimes installed by the MSI are shared with those installed by the MSIX, and are all per-
user only. The Python install manager does not support installing runtimes per-machine. To
emulate a per-machine install, you can use as administrator and add your own system-wide
modifications to , the registry, or the Start [Link] install --
target=<shared location>PATH

When the MSIX is installed, but commands are not available in the environment variable,
they can be found under or , depending on whether it was installed from [Link] or
through the Windows Store. Attempting to run the executable directly from Program Files is
not [Link]%LocalAppData%\Microsoft\WindowsApps\
PythonSoftwareFoundation.PythonManager_3847v3x7pw1km%LocalAppData
%\Microsoft\WindowsApps\
PythonSoftwareFoundation.PythonManager_qbz5n2kfra8p0

To programmatically install the Python install manager, it is easiest to use WinGet, which is
included with all supported versions of Windows:
$> winget install 9NQ7512CXL7T -e --accept-package-agreements --
disable-interactivity

# Optionally run the configuration checker and accept all changes


$> py install --configure -y

To download the Python install manager and install on another machine, the following
WinGet command will download the required files from the Store to your Downloads
directory (add to customize the output location). This also generates a YAML file that appears
to be unnecessary, as the downloaded MSIX can be installed by launching or using the
commands below.-d <location>

$> winget download 9NQ7512CXL7T -e --skip-license --accept-


package-agreements --accept-source-agreements

To programmatically install or uninstall an MSIX using only PowerShell, the Add-


AppxPackage and Remove-AppxPackage PowerShell cmdlets are recommended:

$> Add-AppxPackage C:\Downloads\[Link]


...
$> Get-AppxPackage [Link] |
Remove-AppxPackage

The latest release can be downloaded and installed by Windows by passing the AppInstaller
file to the Add-AppxPackage command. This installs using the MSIX on [Link], and is
only recommended for cases where installing via the Store (interactively or using WinGet) is
not possible.

$> Add-AppxPackage -AppInstallerFile


[Link]
r

Other tools and APIs may also be used to provision an MSIX package for all users on a
machine, but Python does not consider this a supported scenario. We suggest looking into the
PowerShell Add-AppxProvisionedPackage cmdlet, the native
Windows PackageManager class, or the documentation and support for your deployment tool.

Regardless of the install method, users will still need to install their own copies of Python
itself, as there is no way to trigger those installs without being a logged in user. When using
the MSIX, the latest version of Python will be available for all users to install without network
access.

Note that the MSIX downloadable from the Store and from the Python website are subtly
different and cannot be installed at the same time. Wherever possible, we suggest using the
above WinGet commands to download the package from the Store to reduce the risk of setting
up conflicting installs. There are no licensing restrictions on the Python install manager that
would prevent using the Store package in this way.
4.1.11. Administrative configuration
There are a number of options that may be useful for administrators to override configuration
of the Python install manager. These can be used to provide local caching, disable certain
shortcut types, override bundled content. All of the above configuration options may be set, as
well as those below.

Configuration options may be overridden in the registry by setting values under , where the
value name matches the configuration key and the value type is . Note that this key can itself
be customized, but only by modifying the core config file distributed with the Python install
manager. We recommend, however, that registry values are used only to set to a JSON file
containing the full set of overrides. Registry key overrides will replace any other configured
setting, while allows users to further modify settings they may
need.HKEY_LOCAL_MACHINE\Software\Policies\Python\
PyManagerREG_SZbase_configbase_config

Note that most settings with environment variables support those variables because their
default setting specifies the variable. If you override them, the environment variable will no
longer work, unless you override it with another one. For example, the default value of is
literally , which will resolve the variable at load time. If you override the value to , then the
environment variable will no longer be used. If you override the value to , then that
environment variable will be used [Link]%PYTHON_MANAGER_CONFIRM%yes
%CONFIRM%

Configuration settings that are paths are interpreted as relative to the directory containing the
configuration file that specified them.

Administrative configuration options

Config Key Description


The highest priority configuration file to read.
base_config Note that only the built-in configuration file and
the registry can modify this setting.
user_config The second configuration file to read.
additional_config The third configuration file to read.
Registry location to check for overrides. Note that
registry_override_key only the built-in configuration file can modify
this setting.
Read-only directory containing locally cached
bundled_dir
files.
Path or URL to an index to consult when the
install.fallback_source
main index cannot be accessed.
install.enable_shortcut_kind Comma-separated list of shortcut kinds to allow
s (e.g. ). Enabled shortcuts may still be disabled
by ."pep514,start"disable_shortcut_k
Config Key Description
inds
Comma-separated list of shortcut kinds to
exclude (e.g. ). Disabled shortcuts are not
install.disable_shortcut_kin
reactivated
ds
by ."pep514,start"enable_shortcut_ki
nds
True to use hard links for global shortcuts to save
disk space. If false, each shortcut executable is
copied instead. After changing this setting, you
install.hard_link_entrypoint
must run to update existing commands. By
s
default, true. Disabling this may be necessary for
troubleshooting or systems that have issues with
file [Link] install --refresh --force
Registry location to read and write PEP 514
entries into. By
pep514_root
default, .HKEY_CURRENT_USER\Software\
Python
Start menu folder to write shortcuts into. By
start_folder default, . This path is relative to the user’s
Programs [Link]
Path to the active virtual environment. By default,
virtual_env this is , but may be set empty to disable venv
detection.%VIRTUAL_ENV%
True to suppress visible warnings when a shebang
shebang_can_run_anything_sil
launches an application other than a Python
ently
runtime.
4.1.12. Installing free-threaded binaries
Added in version 3.13.

Pre-built distributions of the free-threaded build are available by installing tags with
the suffix.t

$> py install 3.14t


$> py install 3.14t-arm64
$> py install 3.14t-32

This will install and register as normal. If you have no other runtimes installed, then will
launch this one. Otherwise, you will need to use or, if you have added the global aliases
directory to your environment variable, the [Link] -
V:3.14t ...[Link]

4.1.13. Troubleshooting
If your Python install manager does not seem to be working correctly, please work through
these tests and fixes to see if it helps. If not, please report an issue at our bug tracker,
including any relevant log files (written to your directory by default).%TEMP%

Troubleshooting

Symptom Things to try


python gives me
a “command not
found” error or
Did you install the Python install manager?
opens the Store
app when I type it
in my terminal.
Click Start, open “Manage app execution aliases”, and check that the
aliases for “Python (default)” are enabled. If they already are, try
disabling and re-enabling to refresh the command. The “Python (default
windowed)” and “Python install manager” commands may also need
refreshing.
Check that the and commands [Link]
Ensure your variable contains the entry for . The operating system
includes this entry once by default, after other user paths. If removed,
shortcuts will not be [Link]%UserProfile%\AppData\
Local\Microsoft\WindowsApps
py gives me a
“command not
found” error when Did you install the Python install manager?
I type it in my
terminal.
Click Start, open “Manage app execution aliases”, and check that the
aliases for “Python (default)” are enabled. If they already are, try
disabling and re-enabling to refresh the command. The “Python (default
windowed)” and “Python install manager” commands may also need
refreshing.
Ensure your variable contains the entry for . The operating system
includes this entry once by default, after other user paths. If removed,
shortcuts will not be [Link]%UserProfile%\AppData\
Local\Microsoft\WindowsApps
py gives me a
“can’t open file” This usually means you have the legacy launcher installed and it has
error when I type priority over the Python install manager. To remove, click Start, open
commands in my “Installed apps”, search for “Python launcher” and uninstall it.
terminal.
python doesn’t Click Start, open “Installed apps”, look for any existing Python
launch the same runtimes, and either remove them or Modify and disable
Symptom Things to try
runtime as py the [Link]
Click Start, open “Manage app execution aliases”, and check that
your alias is set to “Python (default)”[Link]
python and don’t Check your PYTHON_MANAGER_DEFAULT environment variable
launch the runtime or configuration. The command will show your default based on these
I expectpy settings.default_tagpy list
Installs that are managed by the Python install manager will be chosen
ahead of unmanaged installs. Use to install the runtime you expect, or
configure your default [Link] install
Prerelease and experimental installs that are not managed by the Python
install manager may be chosen ahead of stable releases. Configure your
default tag or uninstall the prerelease runtime and reinstall it
using .py install
pythonw or don’t
launch the same Click Start, open “Manage app execution aliases”, and check that
runtime your and aliases are consistent with your
as or pywpython [Link]
py
pip gives me a
“command not
Have you activated a virtual environment? Run the script in your
found” error when
terminal to activate..venv\Scripts\activate
I type it in my
terminal.
The package may be available but missing the generated executable. We
recommend using the command instead. Running and ensuring that the
global shortcuts directory is on (it will be shown in the command output
if it is not) should make commands such as (and other installed
packages) [Link] -m pippy install --
refreshPATHpip
I installed a
package with but Have you activated a virtual environment? Run the script in your
its command is not terminal to activate..venv\Scripts\activate
[Link]
New packages do not automatically have global shortcuts created by the
Python install manager. Similarly, uninstalled packages do not have
their shortcuts removed. Run to update the global shortcuts for newly
installed [Link] install --refresh
Typing in the
This is a known limitation of the operating system. Either specify before
terminal opens in
the script name, create a batch file containing with the same name as the
a new
script, or install the legacy launcher and select it as the association for
[Link]-
[Link]@py "%~[Link]" %*
[Link]
Symptom Things to try
Drag-dropping This is a known limitation of the operating system. It is supported with
files onto a script the legacy launcher, or with the Python install manager when installed
doesn’t work from the MSI.
I have installed the
It is possible to install from the Store or WinGet, from the MSIX on the
Python install
Python website, and from the MSI, all at once. They are all compatible
manager multiple
and will share configuration and runtimes.
times.
See the earlier Advanced installation section for ways to uninstall the
install manager other than the typical Installed Apps (Add and Remove
Programs) settings page.
My old settings no The new Python install manager no longer supports this configuration
longer file or its settings, and so it will be ignored. See Configuration for
[Link] information about configuration settings.

4.2. The embeddable package


Added in version 3.5.

The embedded distribution is a ZIP file containing a minimal Python environment. It is


intended for acting as part of another application, rather than being directly accessed by end-
users.

To install an embedded distribution, we recommend using with the option:py install--


target

$> py install 3.14-embed --target=<directory>

When extracted, the embedded distribution is (almost) fully isolated from the user’s system,
including environment variables, system registry settings, and installed packages. The
standard library is included as pre-compiled and optimized files in a ZIP, and , , and are all
provided. Tcl/tk (including all dependents, such as Idle), pip and the Python documentation
are not included..[Link]

A default file is included, which further restricts the default search paths (as described below
in Finding modules). This file is intended for embedders to modify as necessary.._pth

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

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

4.2.1. Python application


An application written in Python does not necessarily require users to be aware of that fact.
The embedded distribution may be used in this case 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 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 behave properly. In most cases, a custom
launcher should simply be able to call with a hard-coded command line.Py_Main

The simpler approach is to provide a batch file or generated shortcut that directly calls
the or with the required command-line arguments. In this case, the application will appear to
be Python and not its actual name, and users may have trouble distinguishing it from other
running Python processes or file [Link]

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

4.2.2. Embedding Python


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

As with the application use, packages can be installed to any location as there is an
opportunity to specify search paths before initializing the interpreter. Otherwise, there is no
fundamental differences between using the embedded distribution and a regular installation.

4.3. The [Link] packages


Added in version 3.5.2.

The [Link] package is a reduced size Python environment intended for use on continuous
integration and build systems that do not have a system-wide install of Python. While nuget is
“the package manager for .NET”, it also works perfectly fine for packages containing build-
time tools.

Visit [Link] for the most up-to-date information on using nuget. What follows is a
summary that is sufficient for Python developers.

The command line tool may be downloaded directly from , for example, using curl or
PowerShell. With the tool, the latest version of Python for 64-bit or 32-bit machines is
installed using:[Link]://[Link]/nugetclidl
[Link] install python -ExcludeVersion -OutputDirectory .
[Link] install pythonx86 -ExcludeVersion -OutputDirectory .

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

# Without -ExcludeVersion
.\python.3.5.2\tools\[Link] -V
Python 3.5.2

# With -ExcludeVersion
.\python\tools\[Link] -V
Python 3.5.2

In general, nuget packages are not 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 again. Many CI systems will do this automatically if they do not
preserve files between builds.

Alongside the directory is a directory. This contains a MSBuild properties file that can be
used in a C++ project to reference the Python install. Including the settings will automatically
use the headers and import libraries in your [Link]\[Link]

The package information pages on [Link] are [Link]/packages/python for the 64-
bit version, [Link]/packages/pythonx86 for the 32-bit version,
and [Link]/packages/pythonarm64 for the ARM64 version

4.3.1. Free-threaded packages


Added in version 3.13.

Packages containing free-threaded binaries are named python-freethreaded for the 64-bit
version, pythonx86-freethreaded for the 32-bit version, and pythonarm64-freethreaded for the
ARM64 version. These packages contain both the and entry points, both of which run free
[Link]

4.4. Alternative bundles


Besides the standard CPython distribution, there are modified packages including additional
functionality. The following is a list of popular versions and their key features:

ActivePython
Installer with multi-platform compatibility, documentation, PyWin32

Anaconda
Popular scientific modules (such as numpy, scipy and pandas) and the package
[Link]

Enthought Deployment Manager


“The Next Generation Python Environment and Package Manager”.

Previously Enthought provided Canopy, but it reached end of life in 2016.

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

4.5. Supported Windows versions


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

4.6. Removing the MAX_PATH


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

In the latest versions of Windows, this limitation can be expanded to over


32,000 characters. Your administrator will need to activate the “Enable
Win32 long paths” group policy, or set to in the registry
key .LongPathsEnabled1HKEY_LOCAL_MACHINE\SYSTEM\
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 changing the above option and rebooting, no further configuration is


required.

4.7. UTF-8 mode


Added in version 3.7.

Changed in version 3.15: Python UTF-8 mode is now enabled by default


(PEP 686).
Windows still uses legacy encodings for the system encoding (the ANSI
Code Page). Python uses it for the default encoding of text files
(e.g. [Link]()).

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

The Python UTF-8 Mode, enabled by default, can help by changing the
default text encoding to UTF-8. When the UTF-8 mode is enabled, you can
still use the system encoding (the ANSI Code Page) via the “mbcs” codec.

You can disable the Python UTF-8 Mode via the command line option, or
the environment variable. See PYTHONUTF8 for disabling UTF-8 mode,
and Python install manager for how to modify environment variables.-
X utf8=0PYTHONUTF8=0

Hint

Adding PYTHONUTF8={0,1} to the default environment variables will


affect all Python 3.7+ applications on your system. If you have any Python
3.7+ applications which rely on the legacy system encoding, it is
recommended to set the environment variable temporarily or use the -
X utf8 command 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. Finding modules


These notes supplement the description at The initialization of the [Link]
module search path with detailed Windows notes.

When no file is found, this is how [Link] is populated on


Windows:._pth

 An empty entry is added at the start, which corresponds to the


current directory.
 If the environment variable PYTHONPATH exists, as described
in Environment variables, its entries are added next. Note that on
Windows, paths in this variable must be separated by semicolons,
to distinguish them from the colon used in drive identifiers
( etc.).C:\
 Additional “application paths” can be added in the registry as
subkeys of under both the and hives. Subkeys which have
semicolon-delimited path strings as their default value will cause
each path to be added to [Link]. (Note that all known installers
only use HKLM, so HKCU is typically empty.)\SOFTWARE\
Python\PythonCore{version}\
PythonPathHKEY_CURRENT_USERHKEY_LOCAL_MACHINE
 If the environment variable PYTHONHOME is set, it is assumed as
“Python Home”. Otherwise, the path of the main Python executable
is used to locate a “landmark file” (either or ) to deduce the “Python
Home”. If a Python home is found, the relevant sub-directories
added to [Link] (, , etc) are based on that folder. Otherwise,
the core Python path is constructed from the PythonPath stored in
the [Link]\[Link]-win
 If the Python Home cannot be located, no PYTHONPATH is
specified in the environment, and no registry entries can be found, a
default path with relative entries is used (e.g. , etc)..\Lib;.\
plat-win

If a file is found alongside the main executable or in the directory one level
above the executable, the following variations apply:[Link]

 If 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
[Link]

The end result of all this is:

 When running , or any other .exe in the main Python directory


(either an installed version, or directly from the PCbuild directory),
the core path is deduced, and the core paths in the registry are
ignored. Other “application paths” in the registry are always
[Link]
 When Python is hosted in another .exe (different directory,
embedded via COM, etc), the “Python Home” will not be deduced,
so the core 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, but relative, paths.

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

 Include a file alongside your executable containing the directories


to include. This will ignore paths listed in the registry and
environment variables, and also ignore site unless is
listed.._pthimport site
 If you are loading or in your own executable, explicitly
set PyConfig.module_search_paths before Py_Initiali
zeFromConfig().[Link]
 Clear and/or overwrite PYTHONPATH and set PYTHONHOME before
launching from your [Link]
 If you cannot use the previous suggestions (for example, you are a
distribution that allows people to run directly), ensure that the
landmark file () exists in your install directory. (Note that it will not
be detected inside a ZIP file, but a correctly named ZIP file will be
detected instead.)[Link]\[Link]

These will ensure that the files in a system-wide installation will not take
precedence over the copy of the standard library bundled with your
application. Otherwise, your users may experience problems using your
application. Note that the first suggestion is the best, as the others may still
be susceptible to non-standard paths in the registry and user site-packages.

Changed in version 3.6: Add file support and removes option


from .._pthapplocalpyvenv.cfg

Changed in version 3.6: Add as a potential landmark when directly


adjacent to the [Link]

Deprecated since version 3.6: Modules specified in the registry


under (not ) may be imported
by [Link]. This finder
is enabled on Windows in 3.6.0 and earlier, but may need to be explicitly
added to sys.meta_path in the [Link]

4.9. Additional modules


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

The Windows-specific standard modules are documented in MS Windows


Specific Services.

4.9.1. 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
 Event 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.

See also
Win32 How Do I…?
by Tim Golden
Python and COM
by David and Paul Boddie

4.9.2. cx_Freeze
cx_Freeze wraps Python scripts into executable Windows
programs ( files). When you have done this, you can distribute
your application without requiring your users to install
Python.*.exe

4.10. Compiling Python on


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

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

Check for general information on the build


[Link]/[Link]

For extension modules, consult Building C and C++ Extensions


on Windows.

4.11. The full installer


(deprecated)
Deprecated since version 3.14: This installer is deprecated since
3.14 and will not be produced for Python 3.16 or later.
See Python install manager for the modern installer.

4.11.1. Installation steps


Four Python 3.15 installers are available for download - two each
for the 32-bit 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.

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

If you select “Install Now”:

 You will not need to be an administrator (unless a system


update for the C Runtime Library is required or you install
the Python install manager for all users)
 Python will be installed into your user directory
 The Python install manager will be installed according to
the option at the bottom of the first page
 The standard library, test suite, launcher and pip will be
installed
 If selected, the install directory will 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, you
will need to use this option.
To perform an all-users installation, you should select “Customize
installation”. In this case:

 You may be required to provide administrative credentials


or approval
 Python will be installed into the Program Files directory
 The Python install manager will be installed into the
Windows directory
 Optional features may be selected during installation
 The standard library can be pre-compiled to bytecode
 If selected, the install directory will be added to the
system PATH
 Shortcuts are available for all users
4.11.2. Removing the MAX_PATH
limitation
Windows historically has limited path lengths to 260 characters.
This meant that paths longer than this would not resolve and
errors would result.

In the latest versions of Windows, this limitation can be expanded


to approximately 32,000 characters. Your administrator will need
to activate the “Enable Win32 long paths” group policy, or
set to in the registry
key .LongPathsEnabled1HKEY_LOCAL_MACHINE\
SYSTEM\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 changing the above option, no further configuration is


required.

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


Python.

4.11.3. Installing without UI


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

The following options (found by executing the installer with ) can


be passed into the installer:/?
Name Description
to display progress without requiring user
/passive
interaction
/quiet to install/uninstall without displaying any UI
/simple to prevent user customization
/uninstall to remove Python (without confirmation)
/layout
to pre-download all components
[directory]
/log [filename] to specify log files location

All other options are passed as , where the value is usually to


disable a feature, to enable a feature, or a path. The full list of
available options is shown [Link]=value01

Descript
Name Default
ion
Perform
a
InstallAll system-
0
Users wide
installati
on.
The
installati
TargetDir Selected based on InstallAllUsers
on
directory
The
default
installati
DefaultAl %ProgramFiles%\Python X.Y or %
on
lUsersTar ProgramFiles(x86)%\Python X.
directory
getDir Y
for all-
user
installs
The
default %LocalAppData%\Programs\
DefaultJu install Python\PythonXY or or %LocalApp
stForMeT directory Data%\Programs\Python\
argetDir for just- PythonXY-32%LocalAppData%\
for-me Programs\Python\PythonXY-64
installs
DefaultCu The (empty)
stomTarg default
Descript
Name Default
ion
custom
install
directory
etDir
displaye
d in the
UI
Create
file
associati
Associate
ons if the 1
Files
launcher
is also
installed.
Compile
CompileA all files
0
ll to ..py.
pyc
Prepend
install
and
Scripts
PrependP directori
0
ath es to and
add to P
[Link]
PATHEX
T
Append
install
and
Scripts
AppendPa directori
0
th es to and
add to P
[Link]
PATHEX
T
Shortcuts Create 1
shortcuts
for the
interpret
er,
documen
tation
and
Descript
Name Default
ion
IDLE if
installed.
Install
Include_d
Python 1
oc
manual
Install
Include_d
debug 0
ebug
binaries
Install
develope
r headers
and
libraries.
Include_d Omitting
1
ev this may
lead to
an
unusable
installati
on.
Install an
d related
files.
Omitting
this may
Include_e
lead to 1
xe
an
unusable
installati
[Link]
[Link]
Install P
Include_l ython
1
auncher install
manager.
InstallLau Installs 1
ncherAll the
Users launcher
for all
users.
Also
requires t
o be set
to
Descript
Name Default
ion
1Inclu
de_lau
ncher
Install
standard
library
and
extensio
n
Include_li modules.
1
b Omitting
this may
lead to
an
unusable
installati
on.
Install
bundled
Include_p
pip and 1
ip
setuptool
s
Install
debuggin
Include_s
g 0
ymbols
symbols
(*.pdb)
Install
Tcl/Tk
Include_t
support 1
cltk
and
IDLE
Install
Include_t standard
1
est library
test suite
Install
Include_t
utility 1
ools
scripts
Launcher Only 0
Only installs
the
launcher.
Descript
Name Default
ion
This will
override
most
other
options.
Disable
SimpleIns
most 0
tall
install UI
A
custom
message
to
SimpleIns
display
tallDescri (empty)
when the
ption
simplifie
d install
UI is
used.

For example, to silently install a default, system-wide Python


installation, you could use the following command (from an
elevated command prompt):

[Link] /quiet InstallAllUsers=1


PrependPath=1 Include_test=0

To allow users to easily install a personal copy of Python without


the test suite, you could provide a shortcut with the following
command. This will display a simplified initial page and disallow
customization:

[Link] 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 only recommended for per-user installs when there is also a
system-wide installation that included the launcher.)

The options listed above can also be provided in a file


named 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 always left as strings. This example file sets the
same options as the previous example:[Link]

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

4.11.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 require an internet connection regardless of the selected
features. Note that this download may be bigger than required, but
where a large number of installations are going to be performed it
is very useful to have a locally cached copy.

Execute the following command from Command Prompt to


download all possible required files. Remember to substitute for
the actual name of your installer, and to create layouts in their
own directories to avoid collisions between files with the same
[Link]

[Link] /layout [optional target


directory]

You may also specify the option to hide the progress


display./quiet

4.11.5. Modifying an install


Once Python has been installed, you can add or remove features
through the Programs and Features tool that is part of Windows.
Select the Python entry and choose “Uninstall/Change” to open
the installer in maintenance mode.
“Modify” allows you to add or remove features by modifying the
checkboxes - unchanged checkboxes will not install or remove
anything. Some options cannot be changed in this mode, such as
the install directory; to modify these, you will need to remove and
then reinstall Python completely.

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

“Uninstall” will remove Python entirely, with the exception of


the Python install manager, which has its own entry in Programs
and Features.

4.11.6. Installing free-threaded


binaries
Added in version 3.13.

To install pre-built binaries with free-threading enabled (see PEP


703), you should select “Customize installation”. The second
page of options includes the “Download free-threaded binaries”
checkbox.
Selecting this option will download and install additional binaries
to the same location as the main Python install. The main
executable is called , and other binaries either receive a suffix or a
full ABI suffix. Python source files and bundled third-party
dependencies are shared with the main
[Link]

The free-threaded version is registered as a regular Python install


with the tag (with a or suffix as normal for those platforms). This
allows tools to discover it, and for the Python install manager to
support . Note that the launcher will interpret (or a shebang) as
“the latest 3.x install”, which will prefer the free-threaded binaries
over the regular ones, while will not. If you use the short style of
option, you may prefer to not install the free-threaded binaries at
this [Link] -[Link] -
[Link] -3.13

To specify the install option at the command line, use .


See Installing without downloading for instructions on pre-
emptively downloading the additional binaries for offline install.
The options to include debug symbols and binaries also apply to
the free-threaded builds.Include_freethreaded=1
Free-threaded binaries are also available on [Link].

4.12. Python launcher for


Windows (deprecated)
Deprecated since version 3.14: The launcher and this
documentation have been superseded by the Python Install
Manager described above. This is preserved temporarily for
historical interest.

Added in version 3.3.

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 will locate and execute that version.

Unlike the variable, the launcher will correctly select the most
appropriate version of Python. It will prefer per-user installations
over system-wide ones, and orders by language version rather
than using the most recently installed [Link]

The launcher was originally specified in PEP 397.

4.12.1. Getting started


[Link]. From the command-line
Changed in version 3.6.

System-wide installations of Python 3.3 and later will put the


launcher on your . The launcher is compatible with all available
versions of Python, so it does not matter which version is
installed. To check that the launcher is available, execute the
following command in Command Prompt:PATH

py

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

If you have multiple versions of Python installed (e.g., 3.7 and


3.15) you will have noticed that Python 3.15 was started - to
launch Python 3.7, try the command:

py -3.7
If you want the latest version of Python 2 you have installed, try
the command:

py -2

If you see the following error, you do not have the launcher
installed:

'py' is not recognized as an internal or


external command,
operable program or batch file.

The command:

py --list

displays the currently installed version(s) of Python.

The argument is the short form of the argument, which allows


selecting a specific Python runtime, including those that may have
come from somewhere other than [Link]. Any runtime
registered by following PEP 514 will be discoverable.
The command lists all available runtimes using the format.-x.y-
V:Company/Tag--list-V:

When using the argument, specifying the Company will limit


selection to runtimes from that provider, while specifying only the
Tag will select from all providers. Note that omitting the slash
implies a tag:-V:

# Select any '3.*' tagged runtime


py -V:3

# Select any 'PythonCore' released runtime


py -V:PythonCore/

# Select PythonCore's latest Python 3 runtime


py -V:PythonCore/3

The short form of the argument () only ever selects from core
Python releases, and not other distributions. However, the longer
form () will select from any.-3-V:3

The Company is matched on the full string, case-insensitive. The


Tag is matched on either the full string, or a prefix, provided the
next character is a dot or a hyphen. This allows to match , but
not . Tags are sorted using numerical ordering ( is newer than ),
but are compared using text ( does not match ).-V:3.13.1-
[Link]-V:3.013.1

[Link]. Virtual environments


Added 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 tool) active, the launcher will
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
[Link]

[Link]. From a script


Let’s create a test Python script - create a file called with the
following [Link]

#! python
import sys
[Link]("hello from Python %s\n" %
([Link],))

From the directory in which [Link] lives, execute the command:

py [Link]

You should notice the version number of your latest Python 2.x
installation is printed. Now try changing the first line to be:

#! python3

Re-executing the command 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 have
Python 3.7 installed, try changing the first line to and you should
find the 3.7 version information printed.#! python3.7

Note that unlike interactive use, a bare “python” will use the latest
version of Python 2.x that you have installed. This is for
backward compatibility and for compatibility with Unix, where
the command typically refers to Python [Link]

[Link]. From file associations


The launcher should have been associated with Python files
(i.e. , , files) when it was installed. This means that when you
double-click on one of these files from Windows explorer the
launcher will be used, and therefore you can use the same
facilities described above to have the script specify the version
which should be used..[Link]

The key benefit of this is that a single launcher can support


multiple Python versions at the same time depending on the
contents of the first line.

4.12.2. Shebang lines


If the first line of a script file starts with , it is known as a
“shebang” line. Linux and other Unix like operating systems have
native support for such lines and they are commonly used on such
systems to indicate how a script should be executed. This
launcher allows the 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 use. The supported
virtual commands are:

 /usr/bin/env
 /usr/bin/python
 /usr/local/bin/python
 python

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

#! /usr/bin/python

The default Python or an active virtual environment will be


located and used. As many Python scripts written to work on
Unix will already have this line, you should find these scripts can
be used by the launcher without modification. If you 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

Any of the above virtual commands can be suffixed with an


explicit version (either just the major version, or the major and
minor version). Furthermore the 32-bit version can be requested
by adding “-32” after the minor version. I.e. will request usage of
the 32-bit Python 3.7. If a virtual environment is active, the
version will be ignored and the environment will be
used./usr/bin/python3.7-32
Added in version 3.7: Beginning with python launcher 3.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.e. )./usr/bin/python3-64

Changed in version 3.11: The “-64” suffix is deprecated, and now


implies “any architecture that is not provably i386/32-bit”. To
request a specific environment, use the new argument with the
complete tag.-V:TAG

Changed in version 3.13: Virtual commands referencing now


prefer an active virtual environment rather than searching . This
handles cases where the shebang specifies but is not present in the
active
[Link]/usr/bin/env python3python
[Link]

The form of shebang line has one further special property. Before
looking for installed Python interpreters, this form will search the
executable for a Python executable matching the name provided
as the first argument. This corresponds to the behaviour of the
Unix program, which performs a search. If an executable
matching the first argument after the command cannot be found,
but the argument starts with , it will be handled as described for
the other virtual commands. The environment variable may be set
(to any value) to skip this search
of ./usr/bin/envPATHenvPATHenvpythonPYLAUNCHER_
NO_SEARCH_PATHPATH

Shebang lines that do not match any of these patterns are looked
up in the section of the launcher’s .INI file. This may be used to
handle certain commands in a way that makes sense for your
system. The name of the command must be a single argument (no
spaces in the shebang executable), and the value substituted is the
full path to the executable (additional arguments specified in
the .INI will be quoted as part of the filename).[commands]

[commands]
/bin/xpython=C:\Program Files\XPython\
[Link]

Any commands not found in the .INI file are treated


as Windows executable paths that are absolute or relative to the
directory containing the script file. This is a convenience for
Windows-only scripts, such as those generated by an installer,
since the behavior is not compatible with Unix-style shells. These
paths may be quoted, and may include multiple arguments, after
which the path to the script and any additional arguments will be
appended.
4.12.3. Arguments in shebang lines
The shebang lines can also specify additional options to be passed
to the Python interpreter. For example, if you have a shebang line:

#! /usr/bin/python -v

Then Python will be started with the option-v

4.12.4. Customization
[Link]. Customization via INI files
Two .ini files will be searched by the launcher - in the current
user’s application data directory ( or ) and in the same directory as
the launcher. The same .ini files are used for both the ‘console’
version of the launcher (i.e. [Link]) and for the ‘windows’ version
(i.e. [Link]).[Link]%LOCALAPPDATA%
$env:[Link]

Customization specified in the “application directory” will have


precedence over the one next to the executable, so a user, who
may not have write access to the .ini file next to the launcher, can
override commands in that global .ini file.

[Link]. Customizing default Python


versions
In some cases, a version qualifier can be included in a command
to dictate which version of Python will be 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 bit
implementation shall be requested by adding “-32” or “-64”.

For example, a shebang line of has no version qualifier, while has


a version qualifier which specifies only a major version.#!
python#!python3

If no version qualifiers are found in a command, the environment


variable can be set to specify the default version qualifier. If it is
not set, the default is “3”. The variable can specify any value that
may be passed on the command line, such as “3”, “3.7”, “3.7-32”
or “3.7-64”. (Note that the “-64” option is only available with the
launcher included with Python 3.7 or newer.)PY_PYTHON

If no minor version qualifiers are found, the environment


variable (where is the current major version qualifier as
determined above) can be set to specify the full version. If no
such option is found, the launcher will enumerate the installed
Python versions and use the latest minor release found for the
major version, which is likely, although not guaranteed, to be the
most recently installed version in that
family.PY_PYTHON{major}{major}

On 64-bit Windows with both 32-bit and 64-bit implementations


of the same ([Link]) Python version installed, the 64-bit
version will always be preferred. This will 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 can be
predicted knowing only 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 last). As noted above, 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 and will use


the latest Python 2.x version installed and the
command will use the latest Python 3.x
installed.pythonpython2python3
 The command will not consult any options at all as the
versions are fully specified.python3.7
 If , the commands and will both use the latest installed
Python 3 version.PY_PYTHON=3pythonpython3
 If , the command will use the 32-bit implementation of 3.7
whereas the command will use the latest installed Python
(PY_PYTHON was not considered at all as a major
version was specified.)PY_PYTHON=3.7-
32pythonpython3
 If and , the commands and will both use specifically
3.7PY_PYTHON=3PY_PYTHON3=3.7pythonpython3

In addition to environment variables, the same settings can be


configured in the .INI file used by the launcher. The section in the
INI file is called and the key name will be the same as the
environment variables without the leading 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.[defaults]PY_

For example:

 Setting is equivalent to the INI file


containing:PY_PYTHON=3.7
[defaults]
python=3.7

 Setting and is equivalent to the INI file


containing:PY_PYTHON=3PY_PYTHON3=3.7
[defaults]
python=3
python3=3.7

4.12.5. Diagnostics
If an environment variable 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 particular version was chosen and the exact command-line
used to execute the target Python. It is primarily intended for
testing and debugging.PYLAUNCHER_DEBUG

4.12.6. Dry run


If an environment variable is set (to any value), the launcher will
output the command it would have run, but will not actually
launch Python. This may be useful for tools that want to use the
launcher to detect and then launch Python directly. Note that the
command written to standard output is always encoded using
UTF-8, and may not render correctly in the
console.PYLAUNCHER_DRYRUN

4.12.7. Install on demand


Si une variable d’environnement est fixée (à tout value), et la
version Python demandée n’est pas installée mais est disponible
sur le Microsoft Store, le lanceur tentera de l’installer. Cela peut
nécessiter l’interaction utilisateur est terminée, et il se peut que
vous deviez relancer la
commande.PYLAUNCHER_ALLOW_INSTALL

Une variable supplémentaire provoque le lanceur d’essayer


toujours d’installer Python, même si c’est détecté. C’est
principalement destiné pour les tests (et doit être utilisé
avec ).PYLAUNCHER_ALWAYS_INSTALLPYLAUNCHER_DRYRU
N

4.12.8. Codes de retour


Les codes de sortie suivants peuvent être renvoyés par le lanceur
Python. Malheureusement, il n’y a aucun moyen de les distinguer
du code de sortie de Python lui-même.

Les noms des codes sont ceux utilisés dans les sources, et ne
servent que pour référence. Voilà Il n’y a aucun moyen d’y
accéder ou de les résoudre à part lire cette page. Les candidatures
sont listés par ordre alphabétique des noms.

Nom Valeur Description


A a été retrouvé mais est
RC_BAD_VENV_CFG 107
[Link]
Échec du lancement de
RC_CREATE_PROCESS 101
Python.
Une installation a été
lancée, mais la
RC_INSTALLING 111 commande va Il faut le
relancer une fois
terminé.
Erreur inattendue.
RC_INTERNAL_ERROR 109
Veuillez signaler un bug.
Impossible d’obtenir la
ligne de commande
RC_NO_COMMANDLINE 108
depuis le système
d’exploitation.
Impossible de localiser la
RC_NO_PYTHON 103
version demandée.
A était requis mais pas
RC_NO_VENV_CFG 106
trouvé.[Link]

Vous aimerez peut-être aussi