FAQ : Python et Windows¶
Sommaire
- FAQ : Python et Windows
- Comment exécuter un programme Python sous Windows ?
- Comment rendre des scripts Python exécutables ?
- Pourquoi Python met-il du temps à démarrer ?
- Comment construire un exécutable depuis un script Python ?
- Est-ce qu’un fichier
*.pyd
est la même chose qu’une DLL ? - How can I embed Python into a Windows application?
- Comment empêcher mon éditeur d’utiliser des tabulations dans mes fichiers Python ?
- How do I check for a keypress without blocking?
- How do I emulate os.kill() in Windows?
- Comment décompresser la documentation téléchargée sous Windows ?
Comment exécuter un programme Python sous Windows ?¶
Ce n’est pas forcément une question simple. Si vous êtes déjà familier avec le lancement de programmes depuis la ligne de commande de Windows alors tout semblera évident; Sinon, vous auriez besoin d’être un peu guidé.
Unless you use some sort of integrated development environment, you will end up typing Windows commands into what is variously referred to as a « DOS window » or « Command prompt window ». Usually you can create such a window from your Start menu; under Windows 7 the menu selection is
. You should be able to recognize when you have started such a window because you will see a Windows « command prompt », which usually looks like this:C:\>
la lettre peut être différente, et il peut y avoir d’autres choses à la suite, alors il se peut aussi bien que vous voyez quelque chose tel que:
D:\YourName\Projects\Python>
selon la configuration de votre ordinateur et ce que vous avez récemment fait avec. Une fois que vous avez ouvert cette fenêtre, vous êtes bien partis pour pouvoir lancer des programmes Python.
Retenez que vos scripts Python doivent être traités par un autre programme appelé « l’interpréteur » Python. L’interpréteur lit votre script, le compile en bytecode, et exécute le bytecode pour faire tourner votre programme. Alors, comment faire pour donner votre code Python à l’interpréteur ?
First, you need to make sure that your command window recognises the word
« python » as an instruction to start the interpreter. If you have opened a
command window, you should try entering the command python
and hitting
return.:
C:\Users\YourName> python
You should then see something like:
Python 2.7.3 (default, Apr 10 2012, 22.71:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
You have started the interpreter in « interactive mode ». That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait. This is one of Python’s strongest features. Check it by entering a few expressions of your choice and seeing the results:
>>> print "Hello"
Hello
>>> "Hello" * 3
'HelloHelloHello'
Beaucoup de personnes utilisent le mode interactif comme une calculatrice programmable. Lorsque vous souhaitez sortir du mode interactif de Python, maintenez la touche Ctrl appuyée, puis appuyez sur Z. Validez avec « Entrée » pour retrouver votre ligne de commande Windows.
You may also find that you have a Start-menu entry such as >>>
prompt in a new window. If so, the window will disappear
after you enter the Ctrl-Z character; Windows is running a single « python »
command in the window, and closes it when you terminate the interpreter.
Si, au lieu de vous afficher >>>
la commande python
vous affiche un message semblable à celui-ci :
'python' is not recognized as an internal or external command, operable program or batch file.
ou :
Bad command or filename
alors, vous devez vous assurer que votre ordinateur sait où trouver l’interpréteur Python. Pour cela, vous devez modifier un paramètre, appelé « PATH », qui est une liste des répertoires dans lesquels Windows cherche les programmes.
You should arrange for Python’s installation directory to be added to the PATH of every command window as it starts. If you installed Python fairly recently then the command
dir C:\py*
will probably tell you where it is installed; the usual location is something
like C:\Python27
. Otherwise you will be reduced to a search of your whole
disk … use or hit the Search
button and look for « python.exe ». Supposing you discover that Python is
installed in the C:\Python27
directory (the default at the time of writing),
you should make sure that entering the command
c:\Python27\python
starts up the interpreter as above (and don’t forget you’ll need a « Ctrl-Z » and
an « Enter » to get out of it). Once you have verified the directory, you can
add it to the system path to make it easier to start Python by just running
the python
command. This is currently an option in the installer as of
CPython 2.7.
More information about environment variables can be found on the Using Python on Windows page.
Comment rendre des scripts Python exécutables ?¶
Sous Windows, l’installateur Python associe l’extension .py avec un type de fichier (Python.File) et une commande qui lance l’interpréteur (D:\Program Files\Python\python.exe "%1" %*
). Cela suffit pour pouvoir exécuter les scripts Python depuis la ligne de commande en saisissant foo.py. Si vous souhaitez pouvoir exécuter les scripts en saisissant simplement foo sans l’extension, vous devez ajouter .py au paramètre d’environnement PATHEXT.
Pourquoi Python met-il du temps à démarrer ?¶
Normalement, sous Windows, Python se lance très rapidement, mais parfois des rapports d’erreurs indiquent que Python commence soudain à prendre beaucoup de temps pour démarrer. C’est d’autant plus intrigant que Python fonctionne correctement avec d’autres Windows configurés de façon similaire.
Le problème peut venir d’un antivirus mal configuré. Certains antivirus sont connus pour doubler le temps de démarrage lorsqu’ils sont configurés pour surveiller toutes les lectures du système de fichiers. Essayez de regarder si les antivirus des deux machines sont bien paramétrés à l’identique. McAfee est particulièrement problématique lorsqu’il est paramétré pour surveiller toutes les lectures du système de fichiers.
Comment construire un exécutable depuis un script Python ?¶
See http://www.py2exe.org/ for a distutils extension that allows you to create console and GUI executables from Python code.
Est-ce qu’un fichier *.pyd
est la même chose qu’une DLL ?¶
Yes, .pyd files are dll’s, but there are a few differences. If you have a DLL
named foo.pyd
, then it must have a function initfoo()
. You can then
write Python « import foo », and Python will search for foo.pyd (as well as
foo.py, foo.pyc) and if it finds it, will attempt to call initfoo()
to
initialize it. You do not link your .exe with foo.lib, as that would cause
Windows to require the DLL to be present.
Note that the search path for foo.pyd is PYTHONPATH, not the same as the path
that Windows uses to search for foo.dll. Also, foo.pyd need not be present to
run your program, whereas if you linked your program with a dll, the dll is
required. Of course, foo.pyd is required if you want to say import foo
. In
a DLL, linkage is declared in the source code with __declspec(dllexport)
.
In a .pyd, linkage is defined in a list of available functions.
How can I embed Python into a Windows application?¶
Embedding the Python interpreter in a Windows app can be summarized as follows:
Do _not_ build Python into your .exe file directly. On Windows, Python must be a DLL to handle importing modules that are themselves DLL’s. (This is the first key undocumented fact.) Instead, link to
pythonNN.dll
; it is typically installed inC:\Windows\System
. NN is the Python version, a number such as « 27 » for Python 2.7.You can link to Python in two different ways. Load-time linking means linking against
pythonNN.lib
, while run-time linking means linking againstpythonNN.dll
. (General note:pythonNN.lib
is the so-called « import lib » corresponding topythonNN.dll
. It merely defines symbols for the linker.)Run-time linking greatly simplifies link options; everything happens at run time. Your code must load
pythonNN.dll
using the WindowsLoadLibraryEx()
routine. The code must also use access routines and data inpythonNN.dll
(that is, Python’s C API’s) using pointers obtained by the WindowsGetProcAddress()
routine. Macros can make using these pointers transparent to any C code that calls routines in Python’s C API.Borland note: convert
pythonNN.lib
to OMF format using Coff2Omf.exe first.If you use SWIG, it is easy to create a Python « extension module » that will make the app’s data and methods available to Python. SWIG will handle just about all the grungy details for you. The result is C code that you link into your .exe file (!) You do _not_ have to create a DLL file, and this also simplifies linking.
SWIG will create an init function (a C function) whose name depends on the name of the extension module. For example, if the name of the module is leo, the init function will be called initleo(). If you use SWIG shadow classes, as you should, the init function will be called initleoc(). This initializes a mostly hidden helper class used by the shadow class.
The reason you can link the C code in step 2 into your .exe file is that calling the initialization function is equivalent to importing the module into Python! (This is the second key undocumented fact.)
In short, you can use the following code to initialize the Python interpreter with your extension module.
#include "python.h" ... Py_Initialize(); // Initialize Python. initmyAppc(); // Initialize (import) the helper class. PyRun_SimpleString("import myApp"); // Import the shadow class.
There are two problems with Python’s C API which will become apparent if you use a compiler other than MSVC, the compiler used to build pythonNN.dll.
Problem 1: The so-called « Very High Level » functions that take FILE * arguments will not work in a multi-compiler environment because each compiler’s notion of a struct FILE will be different. From an implementation standpoint these are very _low_ level functions.
Problem 2: SWIG generates the following code when generating wrappers to void functions:
Py_INCREF(Py_None); _resultobj = Py_None; return _resultobj;
Alas, Py_None is a macro that expands to a reference to a complex data structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will fail in a mult-compiler environment. Replace such code by:
return Py_BuildValue("");
It may be possible to use SWIG’s
%typemap
command to make the change automatically, though I have not been able to get this to work (I’m a complete SWIG newbie).Using a Python shell script to put up a Python interpreter window from inside your Windows app is not a good idea; the resulting window will be independent of your app’s windowing system. Rather, you (or the wxPythonWindow class) should create a « native » interpreter window. It is easy to connect that window to the Python interpreter. You can redirect Python’s i/o to _any_ object that supports read and write, so all you need is a Python object (defined in your extension module) that contains read() and write() methods.
Comment empêcher mon éditeur d’utiliser des tabulations dans mes fichiers Python ?¶
La FAQ ne recommande pas l’utilisation des indentations et le guide stylistique de Python, la PEP 8, recommande l’utilisation de 4 espaces dans les codes Python. C’est aussi le comportement par défaut d’Emacs avec Python.
Quel que soit votre éditeur, mélanger des tabulations et des espaces est une mauvaise idée. Visual C++, par exemple, peut être facilement configuré pour utiliser des espaces : allez dans
et pour le type de fichier par défaut, vous devez mettre Tab size et Indent size à 4, puis sélectionner Insert spaces.If you suspect mixed tabs and spaces are causing problems in leading whitespace,
run Python with the -t
switch or run the tabnanny
module to
check a directory tree in batch mode.
How do I check for a keypress without blocking?¶
Use the msvcrt module. This is a standard Windows-specific extension module.
It defines a function kbhit()
which checks whether a keyboard hit is
present, and getch()
which gets one character without echoing it.
How do I emulate os.kill() in Windows?¶
Prior to Python 2.7 and 3.2, to terminate a process, you can use ctypes
:
import ctypes
def kill(pid):
"""kill function for Win32"""
kernel32 = ctypes.windll.kernel32
handle = kernel32.OpenProcess(1, 0, pid)
return (0 != kernel32.TerminateProcess(handle, 0))
In 2.7 and 3.2, os.kill()
is implemented similar to the above function,
with the additional feature of being able to send Ctrl+C and Ctrl+Break
to console subprocesses which are designed to handle those signals. See
os.kill()
for further details.
Comment décompresser la documentation téléchargée sous Windows ?¶
Quelquefois, lorsque vous téléchargez de la documentation avec Windows en utilisant un navigateur internet, l’extension du fichier est .EXE. Il s’agit d’une erreur ; l’extension devrait être .TGZ.
Renommez simplement le fichier téléchargé pour lui donner l’extension .TGZ, puis utilisez WinZip pour le décompresser. Si WinZip ne peut pas décompresser le fichier, téléchargez une version plus à jour (https://www.winzip.com).