blob: 0abe2e98c49f7d90e6a29dab72e0af085aae7bb4 [file] [log] [blame]
Georg Brandl6728c5a2009-10-11 18:31:23 +00001:tocdepth: 2
2
3.. _windows-faq:
4
5=====================
6Python on Windows FAQ
7=====================
8
9.. contents::
10
11How do I run a Python program under Windows?
12--------------------------------------------
13
14This is not necessarily a straightforward question. If you are already familiar
15with running programs from the Windows command line then everything will seem
Brian Curtinbc453ca2012-12-17 00:17:49 -060016obvious; otherwise, you might need a little more guidance.
Georg Brandl6728c5a2009-10-11 18:31:23 +000017
18.. sidebar:: |Python Development on XP|_
19 :subtitle: `Python Development on XP`_
20
21 This series of screencasts aims to get you up and running with Python on
22 Windows XP. The knowledge is distilled into 1.5 hours and will get you up
23 and running with the right Python distribution, coding in your choice of IDE,
24 and debugging and writing solid code with unit-tests.
25
26.. |Python Development on XP| image:: python-video-icon.png
27.. _`Python Development on XP`:
28 http://www.showmedo.com/videos/series?name=pythonOzsvaldPyNewbieSeries
29
30Unless you use some sort of integrated development environment, you will end up
31*typing* Windows commands into what is variously referred to as a "DOS window"
32or "Command prompt window". Usually you can create such a window from your
Brian Curtinbc453ca2012-12-17 00:17:49 -060033Start menu; under Windows 7 the menu selection is :menuselection:`Start -->
Georg Brandl6728c5a2009-10-11 18:31:23 +000034Programs --> Accessories --> Command Prompt`. You should be able to recognize
35when you have started such a window because you will see a Windows "command
36prompt", which usually looks like this::
37
38 C:\>
39
40The letter may be different, and there might be other things after it, so you
41might just as easily see something like::
42
Brian Curtinbc453ca2012-12-17 00:17:49 -060043 D:\YourName\Projects\Python>
Georg Brandl6728c5a2009-10-11 18:31:23 +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 Curtinbc453ca2012-12-17 00:17:49 -060050program called the Python *interpreter*. The interpreter reads your script,
Georg Brandl6728c5a2009-10-11 18:31:23 +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
Brian Curtinbc453ca2012-12-17 00:17:49 -060057return.::
Georg Brandl6728c5a2009-10-11 18:31:23 +000058
Brian Curtinbc453ca2012-12-17 00:17:49 -060059 C:\Users\YourName> python
60
61You should then see something like::
62
63 Python 2.7.3 (default, Apr 10 2012, 22.71:26) [MSC v.1500 32 bit (Intel)] on win32
Georg Brandl6728c5a2009-10-11 18:31:23 +000064 Type "help", "copyright", "credits" or "license" for more information.
65 >>>
66
67You have started the interpreter in "interactive mode". That means you can enter
68Python statements or expressions interactively and have them executed or
69evaluated while you wait. This is one of Python's strongest features. Check it
70by entering a few expressions of your choice and seeing the results::
71
72 >>> print "Hello"
73 Hello
74 >>> "Hello" * 3
75 HelloHelloHello
76
77Many people use the interactive mode as a convenient yet highly programmable
78calculator. When you want to end your interactive Python session, hold the Ctrl
79key down while you enter a Z, then hit the "Enter" key to get back to your
80Windows command prompt.
81
82You may also find that you have a Start-menu entry such as :menuselection:`Start
Brian Curtinbc453ca2012-12-17 00:17:49 -060083--> Programs --> Python 2.7 --> Python (command line)` that results in you
Georg Brandl6728c5a2009-10-11 18:31:23 +000084seeing the ``>>>`` prompt in a new window. If so, the window will disappear
85after you enter the Ctrl-Z character; Windows is running a single "python"
86command in the window, and closes it when you terminate the interpreter.
87
88If the ``python`` command, instead of displaying the interpreter prompt ``>>>``,
89gives you a message like::
90
Brian Curtinbc453ca2012-12-17 00:17:49 -060091 'python' is not recognized as an internal or external command, operable program or batch file.
Georg Brandl6728c5a2009-10-11 18:31:23 +000092
93.. sidebar:: |Adding Python to DOS Path|_
94 :subtitle: `Adding Python to DOS Path`_
95
96 Python is not added to the DOS path by default. This screencast will walk
97 you through the steps to add the correct entry to the `System Path`, allowing
98 Python to be executed from the command-line by all users.
99
100.. |Adding Python to DOS Path| image:: python-video-icon.png
101.. _`Adding Python to DOS Path`:
102 http://showmedo.com/videos/video?name=960000&fromSeriesID=96
103
104
105or::
106
107 Bad command or filename
108
109then you need to make sure that your computer knows where to find the Python
110interpreter. To do this you will have to modify a setting called PATH, which is
111a list of directories where Windows will look for programs.
112
113You should arrange for Python's installation directory to be added to the PATH
114of every command window as it starts. If you installed Python fairly recently
115then the command ::
116
117 dir C:\py*
118
119will probably tell you where it is installed; the usual location is something
Brian Curtinbc453ca2012-12-17 00:17:49 -0600120like ``C:\Python27``. Otherwise you will be reduced to a search of your whole
Georg Brandl6728c5a2009-10-11 18:31:23 +0000121disk ... use :menuselection:`Tools --> Find` or hit the :guilabel:`Search`
122button and look for "python.exe". Supposing you discover that Python is
Brian Curtinbc453ca2012-12-17 00:17:49 -0600123installed in the ``C:\Python27`` directory (the default at the time of writing),
Georg Brandl6728c5a2009-10-11 18:31:23 +0000124you should make sure that entering the command ::
125
Brian Curtinbc453ca2012-12-17 00:17:49 -0600126 c:\Python27\python
Georg Brandl6728c5a2009-10-11 18:31:23 +0000127
128starts up the interpreter as above (and don't forget you'll need a "CTRL-Z" and
Brian Curtinbc453ca2012-12-17 00:17:49 -0600129an "Enter" to get out of it). Once you have verified the directory, you can
130add it to the system path to make it easier to start Python by just running
131the ``python`` command. This is currently an option in the installer as of
132CPython 2.7.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000133
Brian Curtinbc453ca2012-12-17 00:17:49 -0600134More information about environment variables can be found on the
135:ref:`Using Python on Windows <setting-envvars>` page.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000136
Ezio Melotti062d2b52009-12-19 22:41:49 +0000137How do I make Python scripts executable?
Georg Brandl6728c5a2009-10-11 18:31:23 +0000138----------------------------------------
139
Brian Curtinbc453ca2012-12-17 00:17:49 -0600140On Windows, the standard Python installer already associates the .py
Georg Brandl6728c5a2009-10-11 18:31:23 +0000141extension with a file type (Python.File) and gives that file type an open
142command that runs the interpreter (``D:\Program Files\Python\python.exe "%1"
143%*``). This is enough to make scripts executable from the command prompt as
144'foo.py'. If you'd rather be able to execute the script by simple typing 'foo'
145with no extension you need to add .py to the PATHEXT environment variable.
146
Georg Brandl6728c5a2009-10-11 18:31:23 +0000147Why does Python sometimes take so long to start?
148------------------------------------------------
149
150Usually Python starts very quickly on Windows, but occasionally there are bug
151reports that Python suddenly begins to take a long time to start up. This is
152made even more puzzling because Python will work fine on other Windows systems
153which appear to be configured identically.
154
155The problem may be caused by a misconfiguration of virus checking software on
156the problem machine. Some virus scanners have been known to introduce startup
157overhead of two orders of magnitude when the scanner is configured to monitor
158all reads from the filesystem. Try checking the configuration of virus scanning
159software on your systems to ensure that they are indeed configured identically.
160McAfee, when configured to scan all file system read activity, is a particular
161offender.
162
163
Brian Curtinbc453ca2012-12-17 00:17:49 -0600164How do I make an executable from a Python script?
165-------------------------------------------------
Georg Brandl6728c5a2009-10-11 18:31:23 +0000166
Brian Curtinbc453ca2012-12-17 00:17:49 -0600167See http://www.py2exe.org/ for a distutils extension that allows you
168to create console and GUI executables from Python code.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000169
170Is a ``*.pyd`` file the same as a DLL?
171--------------------------------------
172
173.. XXX update for py3k (PyInit_foo)
174
175Yes, .pyd files are dll's, but there are a few differences. If you have a DLL
176named ``foo.pyd``, then it must have a function ``initfoo()``. You can then
177write Python "import foo", and Python will search for foo.pyd (as well as
178foo.py, foo.pyc) and if it finds it, will attempt to call ``initfoo()`` to
179initialize it. You do not link your .exe with foo.lib, as that would cause
180Windows to require the DLL to be present.
181
182Note that the search path for foo.pyd is PYTHONPATH, not the same as the path
183that Windows uses to search for foo.dll. Also, foo.pyd need not be present to
184run your program, whereas if you linked your program with a dll, the dll is
185required. Of course, foo.pyd is required if you want to say ``import foo``. In
186a DLL, linkage is declared in the source code with ``__declspec(dllexport)``.
187In a .pyd, linkage is defined in a list of available functions.
188
189
190How can I embed Python into a Windows application?
191--------------------------------------------------
192
193Embedding the Python interpreter in a Windows app can be summarized as follows:
194
1951. Do _not_ build Python into your .exe file directly. On Windows, Python must
196 be a DLL to handle importing modules that are themselves DLL's. (This is the
Georg Brandlb8d0e362010-11-26 07:53:50 +0000197 first key undocumented fact.) Instead, link to :file:`python{NN}.dll`; it is
198 typically installed in ``C:\Windows\System``. *NN* is the Python version, a
Brian Curtinbc453ca2012-12-17 00:17:49 -0600199 number such as "27" for Python 2.7.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000200
Georg Brandlb8d0e362010-11-26 07:53:50 +0000201 You can link to Python in two different ways. Load-time linking means
202 linking against :file:`python{NN}.lib`, while run-time linking means linking
203 against :file:`python{NN}.dll`. (General note: :file:`python{NN}.lib` is the
204 so-called "import lib" corresponding to :file:`python{NN}.dll`. It merely
205 defines symbols for the linker.)
Georg Brandl6728c5a2009-10-11 18:31:23 +0000206
Georg Brandlb8d0e362010-11-26 07:53:50 +0000207 Run-time linking greatly simplifies link options; everything happens at run
208 time. Your code must load :file:`python{NN}.dll` using the Windows
Georg Brandl6728c5a2009-10-11 18:31:23 +0000209 ``LoadLibraryEx()`` routine. The code must also use access routines and data
210 in :file:`python{NN}.dll` (that is, Python's C API's) using pointers obtained
211 by the Windows ``GetProcAddress()`` routine. Macros can make using these
212 pointers transparent to any C code that calls routines in Python's C API.
213
214 Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe
215 first.
216
Georg Brandlb8d0e362010-11-26 07:53:50 +0000217 .. XXX what about static linking?
218
Georg Brandl6728c5a2009-10-11 18:31:23 +00002192. If you use SWIG, it is easy to create a Python "extension module" that will
220 make the app's data and methods available to Python. SWIG will handle just
221 about all the grungy details for you. The result is C code that you link
222 *into* your .exe file (!) You do _not_ have to create a DLL file, and this
223 also simplifies linking.
224
2253. SWIG will create an init function (a C function) whose name depends on the
226 name of the extension module. For example, if the name of the module is leo,
227 the init function will be called initleo(). If you use SWIG shadow classes,
228 as you should, the init function will be called initleoc(). This initializes
229 a mostly hidden helper class used by the shadow class.
230
231 The reason you can link the C code in step 2 into your .exe file is that
232 calling the initialization function is equivalent to importing the module
233 into Python! (This is the second key undocumented fact.)
234
2354. In short, you can use the following code to initialize the Python interpreter
236 with your extension module.
237
238 .. code-block:: c
239
240 #include "python.h"
241 ...
242 Py_Initialize(); // Initialize Python.
243 initmyAppc(); // Initialize (import) the helper class.
244 PyRun_SimpleString("import myApp") ; // Import the shadow class.
245
2465. There are two problems with Python's C API which will become apparent if you
247 use a compiler other than MSVC, the compiler used to build pythonNN.dll.
248
249 Problem 1: The so-called "Very High Level" functions that take FILE *
250 arguments will not work in a multi-compiler environment because each
251 compiler's notion of a struct FILE will be different. From an implementation
252 standpoint these are very _low_ level functions.
253
254 Problem 2: SWIG generates the following code when generating wrappers to void
255 functions:
256
257 .. code-block:: c
258
259 Py_INCREF(Py_None);
260 _resultobj = Py_None;
261 return _resultobj;
262
263 Alas, Py_None is a macro that expands to a reference to a complex data
264 structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will
265 fail in a mult-compiler environment. Replace such code by:
266
267 .. code-block:: c
268
269 return Py_BuildValue("");
270
271 It may be possible to use SWIG's ``%typemap`` command to make the change
272 automatically, though I have not been able to get this to work (I'm a
273 complete SWIG newbie).
274
2756. Using a Python shell script to put up a Python interpreter window from inside
276 your Windows app is not a good idea; the resulting window will be independent
277 of your app's windowing system. Rather, you (or the wxPythonWindow class)
278 should create a "native" interpreter window. It is easy to connect that
279 window to the Python interpreter. You can redirect Python's i/o to _any_
280 object that supports read and write, so all you need is a Python object
281 (defined in your extension module) that contains read() and write() methods.
282
Georg Brandl6728c5a2009-10-11 18:31:23 +0000283How do I keep editors from inserting tabs into my Python source?
284----------------------------------------------------------------
285
286The FAQ does not recommend using tabs, and the Python style guide, :pep:`8`,
287recommends 4 spaces for distributed Python code; this is also the Emacs
288python-mode default.
289
290Under any editor, mixing tabs and spaces is a bad idea. MSVC is no different in
291this respect, and is easily configured to use spaces: Take :menuselection:`Tools
292--> Options --> Tabs`, and for file type "Default" set "Tab size" and "Indent
293size" to 4, and select the "Insert spaces" radio button.
294
295If you suspect mixed tabs and spaces are causing problems in leading whitespace,
296run Python with the :option:`-t` switch or run ``Tools/Scripts/tabnanny.py`` to
297check a directory tree in batch mode.
298
299
300How do I check for a keypress without blocking?
301-----------------------------------------------
302
303Use the msvcrt module. This is a standard Windows-specific extension module.
304It defines a function ``kbhit()`` which checks whether a keyboard hit is
305present, and ``getch()`` which gets one character without echoing it.
306
307
308How do I emulate os.kill() in Windows?
309--------------------------------------
310
Brian Curtin4e20ab22010-04-12 18:07:21 +0000311Prior to Python 2.7 and 3.2, to terminate a process, you can use :mod:`ctypes`::
Georg Brandlf23f0a22010-03-21 09:51:16 +0000312
313 import ctypes
Georg Brandl6728c5a2009-10-11 18:31:23 +0000314
315 def kill(pid):
316 """kill function for Win32"""
Georg Brandlf23f0a22010-03-21 09:51:16 +0000317 kernel32 = ctypes.windll.kernel32
318 handle = kernel32.OpenProcess(1, 0, pid)
319 return (0 != kernel32.TerminateProcess(handle, 0))
Georg Brandl6728c5a2009-10-11 18:31:23 +0000320
Brian Curtin4e20ab22010-04-12 18:07:21 +0000321In 2.7 and 3.2, :func:`os.kill` is implemented similar to the above function,
322with the additional feature of being able to send CTRL+C and CTRL+BREAK
323to console subprocesses which are designed to handle those signals. See
324:func:`os.kill` for further details.
325
Georg Brandl6728c5a2009-10-11 18:31:23 +0000326How do I extract the downloaded documentation on Windows?
327---------------------------------------------------------
328
329Sometimes, when you download the documentation package to a Windows machine
330using a web browser, the file extension of the saved file ends up being .EXE.
331This is a mistake; the extension should be .TGZ.
332
333Simply rename the downloaded file to have the .TGZ extension, and WinZip will be
334able to handle it. (If your copy of WinZip doesn't, get a newer one from
335http://www.winzip.com.)
336