Outils pour utilisateurs

Outils du site


issue202:python

Python and Windows Greetings fellow Beings. Working in Python means that, many times, the need arises to deal with cross-platform programming. Lately, when starting Python, the majority of us need to use ‘python3’, and, when using pip, we actually need to use ‘pip3’. Some of us have aliased python3 to simply ‘python’ and pip3 to ‘pip’. This is especially easy with pyenv. Unfortunately, users of Microsoft Windows don’t have the ability to use pyenv. So for those Windows users, the problem is worsened because when Python is installed on their machine, it might get set up to use either ‘python’ or ‘python3’ or even ‘’python3.9’ to start Python. This extends to pip as well. To make matters worse, the shebang line (#!/usr/bin/env python3) that should start every Python file, will be wrong when Python is started with “python”.

Python et Windows

Bonjour à tous. Travailler en Python signifie qu'il est souvent nécessaire de s'occuper de la programmation multi-plateforme. Ces derniers temps, lorsque nous démarrons Python, la majorité d'entre nous doit utiliser « python3 » et, lorsque nous utilisons pip, nous devons en fait utiliser « pip3 ».

Certains d'entre nous ont remplacé python3 par « python » et pip3 par « pip ». C'est particulièrement facile avec pyenv. Malheureusement, les utilisateurs de Microsoft Windows n'ont pas la possibilité d'utiliser pyenv. Ainsi, pour ces utilisateurs de Windows, le problème est aggravé car, lorsque Python est installé sur leur machine, il peut être configuré pour utiliser soit « python » soit « python3 » ou même « python3.9 » pour démarrer Python. Cela s'applique également à pip. Pour aggraver les choses, la ligne de « shebang » (la séquence #!/usr/bin/env python3) qui devrait démarrer chaque fichier Python, sera erronée si Python est démarré avec « python ».

So how do you create a batch file to make the startup process simple, and to work in every instance, and create a shebang that will work every time as well? For the last few years, this problem has plagued the Sourceforge PAGE discussion forum. Many users don't bother looking at the previous posts to see if their issue has already been addressed, they seem to think that they are the only ones to have the issue. So the question gets answered multiple times with the same answer. Change the batch file command ‘python3’ to ‘python’ or vice versa. Back in December, the Python-list digest had a thread about the shebang line no longer working correctly when running Python 3.12 under Windows 11. Knowing that this could trouble PAGE users, I started following the thread with interest. As expected, there were a number of responses that contained a “Well, it worked for me” kind of response but many of the responses were seriously trying to help the poster, without a definitive answer.

Alors, comment créer un fichier batch pour simplifier le processus de démarrage, pour qu'il fonctionne dans tous les cas et pour créer un « shebang » (un truc complet) qui fonctionnera également à chaque fois ?

Ces dernières années, ce problème a tourmenté le forum de discussion de PAGE sur Sourceforge. De nombreux utilisateurs ne prennent pas la peine de consulter les messages précédents pour voir si leur problème n'a pas déjà été abordé, car ils semblent penser qu'ils sont les seuls à avoir ce problème. La question est donc traitée plusieurs fois avec la même réponse. Dans le fichier batch, remplacez la commande « python3 » par « python » ou vice versa.

En décembre dernier, le digest de la liste Python contenait un fil de discussion sur le fait que la ligne de « shebang » ne fonctionnait plus correctement lors de l'exécution de Python 3.12 sous Windows 11. Sachant que cela pourrait gêner les utilisateurs de PAGE, j'ai commencé à suivre le fil avec intérêt. Comme prévu, il y a eu un certain nombre de réponses qui contenaient une sorte de « Eh bien, ça a marché pour moi », mais beaucoup de réponses essayaient sérieusement d'aider l'auteur du message, sans réponse définitive.

Eventually, there was a post that pointed to the Python for Windows documentation about using the shebang line. At first, that didn’t fix the issue for the poster, but for me, it gave me some valuable information. However I had to dig deeper into the documentation. Since I run Linux for everything, and fire up a Windows machine only when I absolutely must, I never really looked into the “proper” way to install and start Python when it comes to a Windows machine. The documentation located at https://docs.python.org/3/using/windows.html#python-launcher-for-windows was really an eye-opener for me. I never knew that there was a ‘launcher’ for Windows. I just assumed that Python was Python, and if the command to start Python was ‘python3’, that was what you should use. I couldn’t be more wrong.

Finalement, un post a pointé vers la documentation de Python pour Windows à propos de l'utilisation de la ligne « shebang ». Au début, cela n'a pas résolu le problème pour l'auteur du post, mais pour moi, cela m'a donné des informations précieuses. Cependant, j'ai dû creuser plus profondément dans la documentation.

Comme j'utilise Linux pour tout et que je ne démarre une machine Windows qu'en cas d'absolue nécessité, je n'ai jamais vraiment cherché à savoir comment installer et démarrer Python sur une machine Windows.

La documentation disponible à l'adresse https://docs.python.org/3/using/windows.html#python-launcher-for-windows m'a vraiment ouvert les yeux. Je ne savais pas qu'il existait un « lanceur » pour Windows. Je pensais simplement que Python était Python, et que si la commande pour démarrer Python était « python3 », c'était ce qu'il fallait utiliser. Je ne pouvais pas me tromper davantage.

It turns out that, as far back as Python 3.3, there has been a launcher for Windows, and the command to use the launcher is simply ‘py’ . You can still use python or python3, depending on how your python got installed, but the ‘py’ command will start python regardless. (There is a small caveat here. If Python 2.x was previously installed, the launcher might not have been installed correctly.) If you have two instances of Python on the Windows machine, ‘py’ will start the latest version, but not the last installed version. You can find all the versions that the Windows launcher will provide by doing a ‘py –list’ in the command prompt (shown below).

Il s'avère que, depuis Python 3.3, il existe un lanceur pour Windows, et la commande pour utiliser le lanceur est simplement « py » . Vous pouvez toujours utiliser python ou python3, selon la façon dont votre Python a été installé, mais la commande « py » lancera Python de toute façon. (Il y a une petite mise en garde à ce sujet. Si Python 2.x a été installé précédemment, il se peut que le lanceur n'ait pas été installé correctement).

Si vous avez deux instances de Python sur la machine Windows, la commande « py » lancera la version la plus récente, mais pas la dernière version installée.

Vous pouvez trouver toutes les versions que le lanceur Windows fournira en faisant « py –list » dans l'invite de commande (voir ci-dessous).

In the below screen print, version 3.12 will be the default whenever ‘py’ is called. If you want to use version 3.10 instead, simply call py with the version you want. For example… py -3.10 -v will return 3.10.10 (in my case). There is a curious thing about Python and Windows. Many people have suggested using the ‘where python’ command in the command prompt. However, on my system with three versions of Python installed, what gets returned is… C:\Users\gregg>where python C:\Users\gregg\AppData\Local\Programs\Python\Python312\python.exe C:\Users\gregg\AppData\Local\Microsoft\WindowsApps\python.exe It shows only two versions, not three, and the second version is actually a zero-byte file. This is where the issue with the shebang comes in.

Dans la capture d'écran ci-dessous, la version 3.12 sera la version par défaut chaque fois que « py » sera appelé. Si vous souhaitez utiliser la version 3.10 à la place, appelez simplement py avec la version souhaitée. Par exemple :

py -3.10 -v

renverra la version 3.10.10 (dans mon cas).

Il y a une chose curieuse à propos de Python et Windows. De nombreuses personnes ont suggéré d'utiliser la commande « where python » dans l'invite de commande. Cependant, sur mon système avec trois versions de Python installées, ce qui est retourné est :

C:\Users\gregg>where python C:\Users\gregg\AppData\Local\Programs\Python\Python312\python.exe C:\Users\gregg\AppData\Local\Microsoft\WindowsApps\python.exe

Il n'affiche que deux versions, et non trois, et la deuxième version est en fait un fichier à zéro octet. C'est là qu'intervient le problème du « shebang ».

According to the Python https://docs.python.org/3/using/windows.html#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 “ Of course, the first three versions of the accepted virtual commands couldn’t possibly exist on Windows, but the launcher is supposed to handle them.

D'après le site Python https://docs.python.org/3/using/windows.html#shebang-lines :

« Si la première ligne d'un fichier de script commence par #!, il s'agit d'une ligne « shebang ». Linux et d'autres systèmes d'exploitation de type Unix prennent en charge ces lignes en natif, et elles sont couramment utilisées sur ces systèmes pour indiquer comment un script doit être exécuté. Ce lanceur permet d'utiliser les mêmes fonctions avec les scripts Python sous Windows, et les exemples ci-dessus démontrent leur utilisation.

Pour permettre aux lignes shebang des scripts Python d'être portables entre Unix et Windows, ce lanceur supporte un certain nombre de commandes « virtuelles » pour spécifier l'interpréteur à utiliser. Les commandes virtuelles supportées sont :

/usr/bin/env /usr/bin/python /usr/local/bin/python python “

Bien sûr, les trois premières versions des commandes virtuelles acceptées ne peuvent pas exister sous Windows, mais le lanceur est censé les gérer.

The problem can come from that zero-byte file I pointed out a few moments ago. In fact, when I started fighting the problem on my virtual Windows machine, I had the following zero byte files… C:\Users\gregg\AppData\Local\Microsoft\WindowsApps\python.exe C:\Users\gregg\AppData\Local\Microsoft\WindowsApps\python3.exe For some reason, sometimes on a Windows 11 machine these zero-byte files can cause a message similar to… “Unable to create process using 'C:\usr\bin\env\python” I’ve never heard of this happening on a Windows 10 machine, but I suppose it COULD happen. Anyway, message after message came, suggestions were made, but there was nothing definitive that would fix the user’s problem until January 16. Finally someone suggested that Windows 11 was failing at the zero-byte Alias stub files. The suggestion was to turn off access to the Python stub files.

Le problème peut venir de ce fichier de zéro octet que j'ai signalé il y a quelques instants. En fait, lorsque j'ai commencé à m'attaquer au problème sur ma machine virtuelle Windows, j'avais les fichiers à zéro octet suivants :

C:\Users\gregg\AppData\Local\Microsoft\WindowsApps\python.exe

C:\Users\gregg\AppData\Local\Microsoft\WindowsApps\python3.exe

Pour une raison quelconque, ces fichiers de zéro octet peuvent parfois provoquer, sur une machine Windows 11, un message similaire à :

« Unable to create process using 'C:\usr\bin\env\python » (Impossible de créer un processus à l'aide de 'C:\usr\bin\env\python).

Je n'ai jamais entendu dire que cela se produisait sur une machine Windows 10, mais je suppose que cela PEUT arriver. Quoi qu'il en soit, les messages se sont succédé, des suggestions ont été formulées, mais rien de définitif n'a permis de résoudre le problème de l'utilisateur jusqu'au 16 janvier. Finalement, quelqu'un a suggéré que Windows 11 échouait au niveau des fichiers de stub Alias à zéro octet. La suggestion consistait à désactiver l'accès aux fichiers stub de Python.

That fixed the user’s issue. But how do you get access to the alias settings to turn them off? It isn’t easy to find. Thankfully the poster was able to give a way to find it. Windows has a search box on the panel right next to the start menu. In it, simply type (or even start to type) “Manage app execution aliases”. This will bring up a Settings window that looks something like this. Find the two entries for “App Installer python.exe” and “App Installer python3.exe” and set them to off. Close this window and reboot the machine.

Cela a permis de résoudre le problème de l'utilisateur. Mais comment accéder aux paramètres des alias pour les désactiver ?

Ce n'est pas facile à trouver. Heureusement, l'auteur de l'article a pu donner un moyen de le trouver.

Windows dispose d'un champ de recherche sur le panneau situé juste à côté du menu Démarrer.

Il suffit de taper (ou même de commencer à taper) « Manage app execution aliases » (Gérer les alias d'exécution des applications).

Une fenêtre de paramètres s'affiche alors, qui ressemble à ceci. Trouvez les deux entrées « App Installer python.exe » et « App Installer python3.exe » et désactivez-les.

Fermez cette fenêtre et redémarrez la machine.

Issue fixed! That’s all for this month. I’m in the process of rebuilding my home office from a music room / electronics lab into a true office. We’ll talk again next month. Until next time, as always; stay safe, healthy, positive and creative!

Problème résolu !

C'est tout pour ce mois-ci. Je suis en train de reconstruire mon bureau à domicile pour en faire un véritable bureau.

Nous en reparlerons le mois prochain.

Jusqu'à la prochaine fois, comme toujours, restez en sécurité, en bonne santé, positif et créatif !

issue202/python.txt · Dernière modification : 2024/02/28 12:06 de andre_domenech