blob: 0cfc9dd0f2d7c950e3cf69a9aa02d922a242bd02 [file] [log] [blame]
Georg Brandld7413152009-10-11 21:25:26 +00001:tocdepth: 2
2
Miss Islington (bot)b5719582018-04-09 07:56:44 -07003.. highlightlang:: none
4
Georg Brandld7413152009-10-11 21:25:26 +00005.. _windows-faq:
6
7=====================
8Python on Windows FAQ
9=====================
10
Georg Brandl44ea77b2013-03-28 13:28:44 +010011.. only:: html
12
13 .. contents::
Georg Brandld7413152009-10-11 21:25:26 +000014
Georg Brandl62423cb2009-12-19 17:59:59 +000015.. XXX need review for Python 3.
16 XXX need review for Windows Vista/Seven?
17
18
Georg Brandld7413152009-10-11 21:25:26 +000019How do I run a Python program under Windows?
20--------------------------------------------
21
22This is not necessarily a straightforward question. If you are already familiar
23with running programs from the Windows command line then everything will seem
Brian Curtin655b0c42012-12-16 23:58:09 -060024obvious; otherwise, you might need a little more guidance.
Georg Brandld7413152009-10-11 21:25:26 +000025
Georg Brandld7413152009-10-11 21:25:26 +000026Unless you use some sort of integrated development environment, you will end up
27*typing* Windows commands into what is variously referred to as a "DOS window"
28or "Command prompt window". Usually you can create such a window from your
Brian Curtin655b0c42012-12-16 23:58:09 -060029Start menu; under Windows 7 the menu selection is :menuselection:`Start -->
Georg Brandld7413152009-10-11 21:25:26 +000030Programs --> Accessories --> Command Prompt`. You should be able to recognize
31when you have started such a window because you will see a Windows "command
Miss Islington (bot)b5719582018-04-09 07:56:44 -070032prompt", which usually looks like this:
33
34.. code-block:: doscon
Georg Brandld7413152009-10-11 21:25:26 +000035
36 C:\>
37
38The letter may be different, and there might be other things after it, so you
Miss Islington (bot)b5719582018-04-09 07:56:44 -070039might just as easily see something like:
40
41.. code-block:: doscon
Georg Brandld7413152009-10-11 21:25:26 +000042
Brian Curtin655b0c42012-12-16 23:58:09 -060043 D:\YourName\Projects\Python>
Georg Brandld7413152009-10-11 21:25:26 +000044
45depending on how your computer has been set up and what else you have recently
46done with it. Once you have started such a window, you are well on the way to
47running Python programs.
48
49You need to realize that your Python scripts have to be processed by another
Brian Curtin655b0c42012-12-16 23:58:09 -060050program called the Python *interpreter*. The interpreter reads your script,
Georg Brandld7413152009-10-11 21:25:26 +000051compiles it into bytecodes, and then executes the bytecodes to run your
52program. So, how do you arrange for the interpreter to handle your Python?
53
54First, you need to make sure that your command window recognises the word
55"python" as an instruction to start the interpreter. If you have opened a
56command window, you should try entering the command ``python`` and hitting
Miss Islington (bot)b5719582018-04-09 07:56:44 -070057return:
58
59.. code-block:: doscon
Georg Brandld7413152009-10-11 21:25:26 +000060
Brian Curtin655b0c42012-12-16 23:58:09 -060061 C:\Users\YourName> python
62
Miss Islington (bot)b5719582018-04-09 07:56:44 -070063You should then see something like:
64
65.. code-block:: pycon
Brian Curtin655b0c42012-12-16 23:58:09 -060066
67 Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32
Georg Brandld7413152009-10-11 21:25:26 +000068 Type "help", "copyright", "credits" or "license" for more information.
69 >>>
70
71You have started the interpreter in "interactive mode". That means you can enter
72Python statements or expressions interactively and have them executed or
73evaluated while you wait. This is one of Python's strongest features. Check it
Miss Islington (bot)b5719582018-04-09 07:56:44 -070074by entering a few expressions of your choice and seeing the results:
75
76.. code-block:: pycon
Georg Brandld7413152009-10-11 21:25:26 +000077
Georg Brandl62423cb2009-12-19 17:59:59 +000078 >>> print("Hello")
Georg Brandld7413152009-10-11 21:25:26 +000079 Hello
80 >>> "Hello" * 3
Georg Brandl9205e9e2014-10-06 17:51:09 +020081 'HelloHelloHello'
Georg Brandld7413152009-10-11 21:25:26 +000082
83Many people use the interactive mode as a convenient yet highly programmable
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +030084calculator. When you want to end your interactive Python session, hold the :kbd:`Ctrl`
85key down while you enter a :kbd:`Z`, then hit the ":kbd:`Enter`" key to get back to your
Georg Brandld7413152009-10-11 21:25:26 +000086Windows command prompt.
87
88You may also find that you have a Start-menu entry such as :menuselection:`Start
Brian Curtin655b0c42012-12-16 23:58:09 -060089--> Programs --> Python 3.3 --> Python (command line)` that results in you
Georg Brandld7413152009-10-11 21:25:26 +000090seeing the ``>>>`` prompt in a new window. If so, the window will disappear
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +030091after you enter the :kbd:`Ctrl-Z` character; Windows is running a single "python"
Georg Brandld7413152009-10-11 21:25:26 +000092command in the window, and closes it when you terminate the interpreter.
93
94If the ``python`` command, instead of displaying the interpreter prompt ``>>>``,
95gives you a message like::
96
Brian Curtin655b0c42012-12-16 23:58:09 -060097 'python' is not recognized as an internal or external command, operable program or batch file.
Georg Brandld7413152009-10-11 21:25:26 +000098
Georg Brandld7413152009-10-11 21:25:26 +000099or::
100
101 Bad command or filename
102
103then you need to make sure that your computer knows where to find the Python
104interpreter. To do this you will have to modify a setting called PATH, which is
105a list of directories where Windows will look for programs.
106
107You should arrange for Python's installation directory to be added to the PATH
108of every command window as it starts. If you installed Python fairly recently
109then the command ::
110
111 dir C:\py*
112
113will probably tell you where it is installed; the usual location is something
Brian Curtin655b0c42012-12-16 23:58:09 -0600114like ``C:\Python33``. Otherwise you will be reduced to a search of your whole
Georg Brandld7413152009-10-11 21:25:26 +0000115disk ... use :menuselection:`Tools --> Find` or hit the :guilabel:`Search`
116button and look for "python.exe". Supposing you discover that Python is
Brian Curtin655b0c42012-12-16 23:58:09 -0600117installed in the ``C:\Python33`` directory (the default at the time of writing),
Georg Brandld7413152009-10-11 21:25:26 +0000118you should make sure that entering the command ::
119
Brian Curtin655b0c42012-12-16 23:58:09 -0600120 c:\Python33\python
Georg Brandld7413152009-10-11 21:25:26 +0000121
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300122starts up the interpreter as above (and don't forget you'll need a ":kbd:`Ctrl-Z`" and
123an ":kbd:`Enter`" to get out of it). Once you have verified the directory, you can
Brian Curtin655b0c42012-12-16 23:58:09 -0600124add it to the system path to make it easier to start Python by just running
125the ``python`` command. This is currently an option in the installer as of
126CPython 3.3.
Georg Brandld7413152009-10-11 21:25:26 +0000127
Brian Curtin655b0c42012-12-16 23:58:09 -0600128More information about environment variables can be found on the
129:ref:`Using Python on Windows <setting-envvars>` page.
Georg Brandld7413152009-10-11 21:25:26 +0000130
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000131How do I make Python scripts executable?
Georg Brandld7413152009-10-11 21:25:26 +0000132----------------------------------------
133
Brian Curtin655b0c42012-12-16 23:58:09 -0600134On Windows, the standard Python installer already associates the .py
Georg Brandld7413152009-10-11 21:25:26 +0000135extension with a file type (Python.File) and gives that file type an open
136command that runs the interpreter (``D:\Program Files\Python\python.exe "%1"
137%*``). This is enough to make scripts executable from the command prompt as
138'foo.py'. If you'd rather be able to execute the script by simple typing 'foo'
139with no extension you need to add .py to the PATHEXT environment variable.
140
Georg Brandld7413152009-10-11 21:25:26 +0000141Why does Python sometimes take so long to start?
142------------------------------------------------
143
144Usually Python starts very quickly on Windows, but occasionally there are bug
145reports that Python suddenly begins to take a long time to start up. This is
146made even more puzzling because Python will work fine on other Windows systems
147which appear to be configured identically.
148
149The problem may be caused by a misconfiguration of virus checking software on
150the problem machine. Some virus scanners have been known to introduce startup
151overhead of two orders of magnitude when the scanner is configured to monitor
152all reads from the filesystem. Try checking the configuration of virus scanning
153software on your systems to ensure that they are indeed configured identically.
154McAfee, when configured to scan all file system read activity, is a particular
155offender.
156
157
Brian Curtin655b0c42012-12-16 23:58:09 -0600158How do I make an executable from a Python script?
159-------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000160
Sanyam Khurana1b4587a2017-12-06 22:09:33 +0530161See `cx_Freeze <https://anthony-tuininga.github.io/cx_Freeze/>`_ for a distutils extension
162that allows you to create console and GUI executables from Python code.
Zachary Ware9fc0e992014-01-17 08:59:44 -0600163`py2exe <http://www.py2exe.org/>`_, the most popular extension for building
164Python 2.x-based executables, does not yet support Python 3 but a version that
165does is in development.
166
Georg Brandld7413152009-10-11 21:25:26 +0000167
168Is a ``*.pyd`` file the same as a DLL?
169--------------------------------------
170
Georg Brandld7413152009-10-11 21:25:26 +0000171Yes, .pyd files are dll's, but there are a few differences. If you have a DLL
Zachary Ware9fc0e992014-01-17 08:59:44 -0600172named ``foo.pyd``, then it must have a function ``PyInit_foo()``. You can then
Georg Brandld7413152009-10-11 21:25:26 +0000173write Python "import foo", and Python will search for foo.pyd (as well as
Zachary Ware9fc0e992014-01-17 08:59:44 -0600174foo.py, foo.pyc) and if it finds it, will attempt to call ``PyInit_foo()`` to
Georg Brandld7413152009-10-11 21:25:26 +0000175initialize it. You do not link your .exe with foo.lib, as that would cause
176Windows to require the DLL to be present.
177
178Note that the search path for foo.pyd is PYTHONPATH, not the same as the path
179that Windows uses to search for foo.dll. Also, foo.pyd need not be present to
180run your program, whereas if you linked your program with a dll, the dll is
181required. Of course, foo.pyd is required if you want to say ``import foo``. In
182a DLL, linkage is declared in the source code with ``__declspec(dllexport)``.
183In a .pyd, linkage is defined in a list of available functions.
184
185
186How can I embed Python into a Windows application?
187--------------------------------------------------
188
189Embedding the Python interpreter in a Windows app can be summarized as follows:
190
1911. Do _not_ build Python into your .exe file directly. On Windows, Python must
192 be a DLL to handle importing modules that are themselves DLL's. (This is the
Georg Brandl4985ff22010-10-17 10:14:38 +0000193 first key undocumented fact.) Instead, link to :file:`python{NN}.dll`; it is
194 typically installed in ``C:\Windows\System``. *NN* is the Python version, a
Brian Curtin655b0c42012-12-16 23:58:09 -0600195 number such as "33" for Python 3.3.
Georg Brandld7413152009-10-11 21:25:26 +0000196
Georg Brandl4985ff22010-10-17 10:14:38 +0000197 You can link to Python in two different ways. Load-time linking means
198 linking against :file:`python{NN}.lib`, while run-time linking means linking
199 against :file:`python{NN}.dll`. (General note: :file:`python{NN}.lib` is the
Georg Brandlfc9794a2010-10-17 10:15:50 +0000200 so-called "import lib" corresponding to :file:`python{NN}.dll`. It merely
Georg Brandl4985ff22010-10-17 10:14:38 +0000201 defines symbols for the linker.)
Georg Brandld7413152009-10-11 21:25:26 +0000202
Georg Brandl4985ff22010-10-17 10:14:38 +0000203 Run-time linking greatly simplifies link options; everything happens at run
204 time. Your code must load :file:`python{NN}.dll` using the Windows
Georg Brandld7413152009-10-11 21:25:26 +0000205 ``LoadLibraryEx()`` routine. The code must also use access routines and data
206 in :file:`python{NN}.dll` (that is, Python's C API's) using pointers obtained
207 by the Windows ``GetProcAddress()`` routine. Macros can make using these
208 pointers transparent to any C code that calls routines in Python's C API.
209
210 Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe
211 first.
212
Georg Brandl4985ff22010-10-17 10:14:38 +0000213 .. XXX what about static linking?
214
Georg Brandld7413152009-10-11 21:25:26 +00002152. If you use SWIG, it is easy to create a Python "extension module" that will
216 make the app's data and methods available to Python. SWIG will handle just
217 about all the grungy details for you. The result is C code that you link
218 *into* your .exe file (!) You do _not_ have to create a DLL file, and this
219 also simplifies linking.
220
2213. SWIG will create an init function (a C function) whose name depends on the
222 name of the extension module. For example, if the name of the module is leo,
223 the init function will be called initleo(). If you use SWIG shadow classes,
224 as you should, the init function will be called initleoc(). This initializes
225 a mostly hidden helper class used by the shadow class.
226
227 The reason you can link the C code in step 2 into your .exe file is that
228 calling the initialization function is equivalent to importing the module
229 into Python! (This is the second key undocumented fact.)
230
2314. In short, you can use the following code to initialize the Python interpreter
232 with your extension module.
233
234 .. code-block:: c
235
236 #include "python.h"
237 ...
238 Py_Initialize(); // Initialize Python.
239 initmyAppc(); // Initialize (import) the helper class.
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200240 PyRun_SimpleString("import myApp"); // Import the shadow class.
Georg Brandld7413152009-10-11 21:25:26 +0000241
2425. There are two problems with Python's C API which will become apparent if you
243 use a compiler other than MSVC, the compiler used to build pythonNN.dll.
244
245 Problem 1: The so-called "Very High Level" functions that take FILE *
246 arguments will not work in a multi-compiler environment because each
247 compiler's notion of a struct FILE will be different. From an implementation
248 standpoint these are very _low_ level functions.
249
250 Problem 2: SWIG generates the following code when generating wrappers to void
251 functions:
252
253 .. code-block:: c
254
255 Py_INCREF(Py_None);
256 _resultobj = Py_None;
257 return _resultobj;
258
259 Alas, Py_None is a macro that expands to a reference to a complex data
260 structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will
261 fail in a mult-compiler environment. Replace such code by:
262
263 .. code-block:: c
264
265 return Py_BuildValue("");
266
267 It may be possible to use SWIG's ``%typemap`` command to make the change
268 automatically, though I have not been able to get this to work (I'm a
269 complete SWIG newbie).
270
2716. Using a Python shell script to put up a Python interpreter window from inside
272 your Windows app is not a good idea; the resulting window will be independent
273 of your app's windowing system. Rather, you (or the wxPythonWindow class)
274 should create a "native" interpreter window. It is easy to connect that
275 window to the Python interpreter. You can redirect Python's i/o to _any_
276 object that supports read and write, so all you need is a Python object
277 (defined in your extension module) that contains read() and write() methods.
278
Georg Brandld7413152009-10-11 21:25:26 +0000279How do I keep editors from inserting tabs into my Python source?
280----------------------------------------------------------------
281
282The FAQ does not recommend using tabs, and the Python style guide, :pep:`8`,
283recommends 4 spaces for distributed Python code; this is also the Emacs
284python-mode default.
285
286Under any editor, mixing tabs and spaces is a bad idea. MSVC is no different in
287this respect, and is easily configured to use spaces: Take :menuselection:`Tools
288--> Options --> Tabs`, and for file type "Default" set "Tab size" and "Indent
289size" to 4, and select the "Insert spaces" radio button.
290
Victor Stinner2b501862017-02-13 15:30:05 +0100291Python raises :exc:`IndentationError` or :exc:`TabError` if mixed tabs
Jim DeLaHunt3d707be2017-02-13 05:57:13 -0800292and spaces are causing problems in leading whitespace.
Victor Stinner2b501862017-02-13 15:30:05 +0100293You may also run the :mod:`tabnanny` module to check a directory tree
Jim DeLaHunt3d707be2017-02-13 05:57:13 -0800294in batch mode.
Georg Brandld7413152009-10-11 21:25:26 +0000295
296
297How do I check for a keypress without blocking?
298-----------------------------------------------
299
300Use the msvcrt module. This is a standard Windows-specific extension module.
301It defines a function ``kbhit()`` which checks whether a keyboard hit is
302present, and ``getch()`` which gets one character without echoing it.
303
304
305How do I emulate os.kill() in Windows?
306--------------------------------------
307
Miss Islington (bot)b5719582018-04-09 07:56:44 -0700308Prior to Python 2.7 and 3.2, to terminate a process, you can use :mod:`ctypes`:
309
310.. code-block:: python
Georg Brandlff24c8e2010-03-21 09:52:24 +0000311
312 import ctypes
Georg Brandld7413152009-10-11 21:25:26 +0000313
314 def kill(pid):
315 """kill function for Win32"""
Georg Brandlff24c8e2010-03-21 09:52:24 +0000316 kernel32 = ctypes.windll.kernel32
317 handle = kernel32.OpenProcess(1, 0, pid)
318 return (0 != kernel32.TerminateProcess(handle, 0))
Georg Brandld7413152009-10-11 21:25:26 +0000319
Brian Curtinf4ed2062010-04-12 18:10:10 +0000320In 2.7 and 3.2, :func:`os.kill` is implemented similar to the above function,
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300321with the additional feature of being able to send :kbd:`Ctrl+C` and :kbd:`Ctrl+Break`
Brian Curtinf4ed2062010-04-12 18:10:10 +0000322to console subprocesses which are designed to handle those signals. See
323:func:`os.kill` for further details.
324
Georg Brandld7413152009-10-11 21:25:26 +0000325How do I extract the downloaded documentation on Windows?
326---------------------------------------------------------
327
328Sometimes, when you download the documentation package to a Windows machine
329using a web browser, the file extension of the saved file ends up being .EXE.
330This is a mistake; the extension should be .TGZ.
331
332Simply rename the downloaded file to have the .TGZ extension, and WinZip will be
333able to handle it. (If your copy of WinZip doesn't, get a newer one from
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300334https://www.winzip.com.)
Georg Brandld7413152009-10-11 21:25:26 +0000335