blob: 2a19c981fc51d8ce6c2121c8a1050be4a95b80b0 [file] [log] [blame]
Georg Brandld7413152009-10-11 21:25:26 +00001:tocdepth: 2
2
3.. _windows-faq:
4
5=====================
6Python on Windows FAQ
7=====================
8
9.. contents::
10
Georg Brandl62423cb2009-12-19 17:59:59 +000011.. XXX need review for Python 3.
12 XXX need review for Windows Vista/Seven?
13
14
Georg Brandld7413152009-10-11 21:25:26 +000015How do I run a Python program under Windows?
16--------------------------------------------
17
18This is not necessarily a straightforward question. If you are already familiar
19with running programs from the Windows command line then everything will seem
20obvious; otherwise, you might need a little more guidance. There are also
21differences between Windows 95, 98, NT, ME, 2000 and XP which can add to the
22confusion.
23
24.. sidebar:: |Python Development on XP|_
25 :subtitle: `Python Development on XP`_
26
27 This series of screencasts aims to get you up and running with Python on
28 Windows XP. The knowledge is distilled into 1.5 hours and will get you up
29 and running with the right Python distribution, coding in your choice of IDE,
30 and debugging and writing solid code with unit-tests.
31
32.. |Python Development on XP| image:: python-video-icon.png
33.. _`Python Development on XP`:
34 http://www.showmedo.com/videos/series?name=pythonOzsvaldPyNewbieSeries
35
36Unless you use some sort of integrated development environment, you will end up
37*typing* Windows commands into what is variously referred to as a "DOS window"
38or "Command prompt window". Usually you can create such a window from your
39Start menu; under Windows 2000 the menu selection is :menuselection:`Start -->
40Programs --> Accessories --> Command Prompt`. You should be able to recognize
41when you have started such a window because you will see a Windows "command
42prompt", which usually looks like this::
43
44 C:\>
45
46The letter may be different, and there might be other things after it, so you
47might just as easily see something like::
48
49 D:\Steve\Projects\Python>
50
51depending on how your computer has been set up and what else you have recently
52done with it. Once you have started such a window, you are well on the way to
53running Python programs.
54
55You need to realize that your Python scripts have to be processed by another
56program called the Python interpreter. The interpreter reads your script,
57compiles it into bytecodes, and then executes the bytecodes to run your
58program. So, how do you arrange for the interpreter to handle your Python?
59
60First, you need to make sure that your command window recognises the word
61"python" as an instruction to start the interpreter. If you have opened a
62command window, you should try entering the command ``python`` and hitting
63return. You should then see something like::
64
65 Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
66 Type "help", "copyright", "credits" or "license" for more information.
67 >>>
68
69You have started the interpreter in "interactive mode". That means you can enter
70Python statements or expressions interactively and have them executed or
71evaluated while you wait. This is one of Python's strongest features. Check it
72by entering a few expressions of your choice and seeing the results::
73
Georg Brandl62423cb2009-12-19 17:59:59 +000074 >>> print("Hello")
Georg Brandld7413152009-10-11 21:25:26 +000075 Hello
76 >>> "Hello" * 3
77 HelloHelloHello
78
79Many people use the interactive mode as a convenient yet highly programmable
80calculator. When you want to end your interactive Python session, hold the Ctrl
81key down while you enter a Z, then hit the "Enter" key to get back to your
82Windows command prompt.
83
84You may also find that you have a Start-menu entry such as :menuselection:`Start
85--> Programs --> Python 2.2 --> Python (command line)` that results in you
86seeing the ``>>>`` prompt in a new window. If so, the window will disappear
87after you enter the Ctrl-Z character; Windows is running a single "python"
88command in the window, and closes it when you terminate the interpreter.
89
90If the ``python`` command, instead of displaying the interpreter prompt ``>>>``,
91gives you a message like::
92
93 'python' is not recognized as an internal or external command,
94 operable program or batch file.
95
96.. sidebar:: |Adding Python to DOS Path|_
97 :subtitle: `Adding Python to DOS Path`_
98
99 Python is not added to the DOS path by default. This screencast will walk
100 you through the steps to add the correct entry to the `System Path`, allowing
101 Python to be executed from the command-line by all users.
102
103.. |Adding Python to DOS Path| image:: python-video-icon.png
104.. _`Adding Python to DOS Path`:
105 http://showmedo.com/videos/video?name=960000&fromSeriesID=96
106
107
108or::
109
110 Bad command or filename
111
112then you need to make sure that your computer knows where to find the Python
113interpreter. To do this you will have to modify a setting called PATH, which is
114a list of directories where Windows will look for programs.
115
116You should arrange for Python's installation directory to be added to the PATH
117of every command window as it starts. If you installed Python fairly recently
118then the command ::
119
120 dir C:\py*
121
122will probably tell you where it is installed; the usual location is something
123like ``C:\Python23``. Otherwise you will be reduced to a search of your whole
124disk ... use :menuselection:`Tools --> Find` or hit the :guilabel:`Search`
125button and look for "python.exe". Supposing you discover that Python is
126installed in the ``C:\Python23`` directory (the default at the time of writing),
127you should make sure that entering the command ::
128
129 c:\Python23\python
130
131starts up the interpreter as above (and don't forget you'll need a "CTRL-Z" and
132an "Enter" to get out of it). Once you have verified the directory, you need to
133add it to the start-up routines your computer goes through. For older versions
134of Windows the easiest way to do this is to edit the ``C:\AUTOEXEC.BAT``
135file. You would want to add a line like the following to ``AUTOEXEC.BAT``::
136
137 PATH C:\Python23;%PATH%
138
139For Windows NT, 2000 and (I assume) XP, you will need to add a string such as ::
140
141 ;C:\Python23
142
143to the current setting for the PATH environment variable, which you will find in
144the properties window of "My Computer" under the "Advanced" tab. Note that if
145you have sufficient privilege you might get a choice of installing the settings
146either for the Current User or for System. The latter is preferred if you want
147everybody to be able to run Python on the machine.
148
149If you aren't confident doing any of these manipulations yourself, ask for help!
150At this stage you may want to reboot your system to make absolutely sure the new
151setting has taken effect. You probably won't need to reboot for Windows NT, XP
152or 2000. You can also avoid it in earlier versions by editing the file
153``C:\WINDOWS\COMMAND\CMDINIT.BAT`` instead of ``AUTOEXEC.BAT``.
154
155You should now be able to start a new command window, enter ``python`` at the
156``C:\>`` (or whatever) prompt, and see the ``>>>`` prompt that indicates the
157Python interpreter is reading interactive commands.
158
159Let's suppose you have a program called ``pytest.py`` in directory
160``C:\Steve\Projects\Python``. A session to run that program might look like
161this::
162
163 C:\> cd \Steve\Projects\Python
164 C:\Steve\Projects\Python> python pytest.py
165
166Because you added a file name to the command to start the interpreter, when it
167starts up it reads the Python script in the named file, compiles it, executes
168it, and terminates, so you see another ``C:\>`` prompt. You might also have
169entered ::
170
171 C:\> python \Steve\Projects\Python\pytest.py
172
173if you hadn't wanted to change your current directory.
174
175Under NT, 2000 and XP you may well find that the installation process has also
176arranged that the command ``pytest.py`` (or, if the file isn't in the current
177directory, ``C:\Steve\Projects\Python\pytest.py``) will automatically recognize
178the ".py" extension and run the Python interpreter on the named file. Using this
179feature is fine, but *some* versions of Windows have bugs which mean that this
180form isn't exactly equivalent to using the interpreter explicitly, so be
181careful.
182
183The important things to remember are:
184
1851. Start Python from the Start Menu, or make sure the PATH is set correctly so
186 Windows can find the Python interpreter. ::
187
188 python
189
190 should give you a '>>>' prompt from the Python interpreter. Don't forget the
191 CTRL-Z and ENTER to terminate the interpreter (and, if you started the window
192 from the Start Menu, make the window disappear).
193
1942. Once this works, you run programs with commands::
195
196 python {program-file}
197
1983. When you know the commands to use you can build Windows shortcuts to run the
199 Python interpreter on any of your scripts, naming particular working
200 directories, and adding them to your menus. Take a look at ::
201
202 python --help
203
204 if your needs are complex.
205
2064. Interactive mode (where you see the ``>>>`` prompt) is best used for checking
207 that individual statements and expressions do what you think they will, and
208 for developing code by experiment.
209
210
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000211How do I make Python scripts executable?
Georg Brandld7413152009-10-11 21:25:26 +0000212----------------------------------------
213
214On Windows 2000, the standard Python installer already associates the .py
215extension with a file type (Python.File) and gives that file type an open
216command that runs the interpreter (``D:\Program Files\Python\python.exe "%1"
217%*``). This is enough to make scripts executable from the command prompt as
218'foo.py'. If you'd rather be able to execute the script by simple typing 'foo'
219with no extension you need to add .py to the PATHEXT environment variable.
220
221On Windows NT, the steps taken by the installer as described above allow you to
222run a script with 'foo.py', but a longtime bug in the NT command processor
223prevents you from redirecting the input or output of any script executed in this
224way. This is often important.
225
226The incantation for making a Python script executable under WinNT is to give the
227file an extension of .cmd and add the following as the first line::
228
229 @setlocal enableextensions & python -x %~f0 %* & goto :EOF
230
231
232Why does Python sometimes take so long to start?
233------------------------------------------------
234
235Usually Python starts very quickly on Windows, but occasionally there are bug
236reports that Python suddenly begins to take a long time to start up. This is
237made even more puzzling because Python will work fine on other Windows systems
238which appear to be configured identically.
239
240The problem may be caused by a misconfiguration of virus checking software on
241the problem machine. Some virus scanners have been known to introduce startup
242overhead of two orders of magnitude when the scanner is configured to monitor
243all reads from the filesystem. Try checking the configuration of virus scanning
244software on your systems to ensure that they are indeed configured identically.
245McAfee, when configured to scan all file system read activity, is a particular
246offender.
247
248
249Where is Freeze for Windows?
250----------------------------
251
252"Freeze" is a program that allows you to ship a Python program as a single
253stand-alone executable file. It is *not* a compiler; your programs don't run
254any faster, but they are more easily distributable, at least to platforms with
255the same OS and CPU. Read the README file of the freeze program for more
256disclaimers.
257
258You can use freeze on Windows, but you must download the source tree (see
259http://www.python.org/download/source). The freeze program is in the
260``Tools\freeze`` subdirectory of the source tree.
261
262You need the Microsoft VC++ compiler, and you probably need to build Python.
263The required project files are in the PCbuild directory.
264
265
266Is a ``*.pyd`` file the same as a DLL?
267--------------------------------------
268
269.. XXX update for py3k (PyInit_foo)
270
271Yes, .pyd files are dll's, but there are a few differences. If you have a DLL
272named ``foo.pyd``, then it must have a function ``initfoo()``. You can then
273write Python "import foo", and Python will search for foo.pyd (as well as
274foo.py, foo.pyc) and if it finds it, will attempt to call ``initfoo()`` to
275initialize it. You do not link your .exe with foo.lib, as that would cause
276Windows to require the DLL to be present.
277
278Note that the search path for foo.pyd is PYTHONPATH, not the same as the path
279that Windows uses to search for foo.dll. Also, foo.pyd need not be present to
280run your program, whereas if you linked your program with a dll, the dll is
281required. Of course, foo.pyd is required if you want to say ``import foo``. In
282a DLL, linkage is declared in the source code with ``__declspec(dllexport)``.
283In a .pyd, linkage is defined in a list of available functions.
284
285
286How can I embed Python into a Windows application?
287--------------------------------------------------
288
289Embedding the Python interpreter in a Windows app can be summarized as follows:
290
2911. Do _not_ build Python into your .exe file directly. On Windows, Python must
292 be a DLL to handle importing modules that are themselves DLL's. (This is the
293 first key undocumented fact.) Instead, link to :file:`python{NN}.dll`; it is
294 typically installed in ``C:\Windows\System``. NN is the Python version, a
295 number such as "23" for Python 2.3.
296
297 You can link to Python statically or dynamically. Linking statically means
298 linking against :file:`python{NN}.lib`, while dynamically linking means
299 linking against :file:`python{NN}.dll`. The drawback to dynamic linking is
300 that your app won't run if :file:`python{NN}.dll` does not exist on your
301 system. (General note: :file:`python{NN}.lib` is the so-called "import lib"
302 corresponding to :file:`python.dll`. It merely defines symbols for the
303 linker.)
304
305 Linking dynamically greatly simplifies link options; everything happens at
306 run time. Your code must load :file:`python{NN}.dll` using the Windows
307 ``LoadLibraryEx()`` routine. The code must also use access routines and data
308 in :file:`python{NN}.dll` (that is, Python's C API's) using pointers obtained
309 by the Windows ``GetProcAddress()`` routine. Macros can make using these
310 pointers transparent to any C code that calls routines in Python's C API.
311
312 Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe
313 first.
314
3152. If you use SWIG, it is easy to create a Python "extension module" that will
316 make the app's data and methods available to Python. SWIG will handle just
317 about all the grungy details for you. The result is C code that you link
318 *into* your .exe file (!) You do _not_ have to create a DLL file, and this
319 also simplifies linking.
320
3213. SWIG will create an init function (a C function) whose name depends on the
322 name of the extension module. For example, if the name of the module is leo,
323 the init function will be called initleo(). If you use SWIG shadow classes,
324 as you should, the init function will be called initleoc(). This initializes
325 a mostly hidden helper class used by the shadow class.
326
327 The reason you can link the C code in step 2 into your .exe file is that
328 calling the initialization function is equivalent to importing the module
329 into Python! (This is the second key undocumented fact.)
330
3314. In short, you can use the following code to initialize the Python interpreter
332 with your extension module.
333
334 .. code-block:: c
335
336 #include "python.h"
337 ...
338 Py_Initialize(); // Initialize Python.
339 initmyAppc(); // Initialize (import) the helper class.
340 PyRun_SimpleString("import myApp") ; // Import the shadow class.
341
3425. There are two problems with Python's C API which will become apparent if you
343 use a compiler other than MSVC, the compiler used to build pythonNN.dll.
344
345 Problem 1: The so-called "Very High Level" functions that take FILE *
346 arguments will not work in a multi-compiler environment because each
347 compiler's notion of a struct FILE will be different. From an implementation
348 standpoint these are very _low_ level functions.
349
350 Problem 2: SWIG generates the following code when generating wrappers to void
351 functions:
352
353 .. code-block:: c
354
355 Py_INCREF(Py_None);
356 _resultobj = Py_None;
357 return _resultobj;
358
359 Alas, Py_None is a macro that expands to a reference to a complex data
360 structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will
361 fail in a mult-compiler environment. Replace such code by:
362
363 .. code-block:: c
364
365 return Py_BuildValue("");
366
367 It may be possible to use SWIG's ``%typemap`` command to make the change
368 automatically, though I have not been able to get this to work (I'm a
369 complete SWIG newbie).
370
3716. Using a Python shell script to put up a Python interpreter window from inside
372 your Windows app is not a good idea; the resulting window will be independent
373 of your app's windowing system. Rather, you (or the wxPythonWindow class)
374 should create a "native" interpreter window. It is easy to connect that
375 window to the Python interpreter. You can redirect Python's i/o to _any_
376 object that supports read and write, so all you need is a Python object
377 (defined in your extension module) that contains read() and write() methods.
378
379
380How do I use Python for CGI?
381----------------------------
382
383On the Microsoft IIS server or on the Win95 MS Personal Web Server you set up
384Python in the same way that you would set up any other scripting engine.
385
386Run regedt32 and go to::
387
388 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\ScriptMap
389
390and enter the following line (making any specific changes that your system may
391need)::
392
393 .py :REG_SZ: c:\<path to python>\python.exe -u %s %s
394
395This line will allow you to call your script with a simple reference like:
Georg Brandl495f7b52009-10-27 15:28:25 +0000396``http://yourserver/scripts/yourscript.py`` provided "scripts" is an
397"executable" directory for your server (which it usually is by default). The
398:option:`-u` flag specifies unbuffered and binary mode for stdin - needed when
399working with binary data.
Georg Brandld7413152009-10-11 21:25:26 +0000400
401In addition, it is recommended that using ".py" may not be a good idea for the
402file extensions when used in this context (you might want to reserve ``*.py``
403for support modules and use ``*.cgi`` or ``*.cgp`` for "main program" scripts).
404
405In order to set up Internet Information Services 5 to use Python for CGI
406processing, please see the following links:
407
408 http://www.e-coli.net/pyiis_server.html (for Win2k Server)
409 http://www.e-coli.net/pyiis.html (for Win2k pro)
410
411Configuring Apache is much simpler. In the Apache configuration file
412``httpd.conf``, add the following line at the end of the file::
413
414 ScriptInterpreterSource Registry
415
416Then, give your Python CGI-scripts the extension .py and put them in the cgi-bin
417directory.
418
419
420How do I keep editors from inserting tabs into my Python source?
421----------------------------------------------------------------
422
423The FAQ does not recommend using tabs, and the Python style guide, :pep:`8`,
424recommends 4 spaces for distributed Python code; this is also the Emacs
425python-mode default.
426
427Under any editor, mixing tabs and spaces is a bad idea. MSVC is no different in
428this respect, and is easily configured to use spaces: Take :menuselection:`Tools
429--> Options --> Tabs`, and for file type "Default" set "Tab size" and "Indent
430size" to 4, and select the "Insert spaces" radio button.
431
432If you suspect mixed tabs and spaces are causing problems in leading whitespace,
433run Python with the :option:`-t` switch or run ``Tools/Scripts/tabnanny.py`` to
434check a directory tree in batch mode.
435
436
437How do I check for a keypress without blocking?
438-----------------------------------------------
439
440Use the msvcrt module. This is a standard Windows-specific extension module.
441It defines a function ``kbhit()`` which checks whether a keyboard hit is
442present, and ``getch()`` which gets one character without echoing it.
443
444
445How do I emulate os.kill() in Windows?
446--------------------------------------
447
448Use win32api::
449
450 def kill(pid):
451 """kill function for Win32"""
452 import win32api
453 handle = win32api.OpenProcess(1, 0, pid)
454 return (0 != win32api.TerminateProcess(handle, 0))
455
456
457Why does os.path.isdir() fail on NT shared directories?
458-------------------------------------------------------
459
460The solution appears to be always append the "\\" on the end of shared
461drives.
462
463 >>> import os
464 >>> os.path.isdir( '\\\\rorschach\\public')
465 0
466 >>> os.path.isdir( '\\\\rorschach\\public\\')
467 1
468
469It helps to think of share points as being like drive letters. Example::
470
471 k: is not a directory
472 k:\ is a directory
473 k:\media is a directory
474 k:\media\ is not a directory
475
476The same rules apply if you substitute "k:" with "\\conky\foo"::
477
478 \\conky\foo is not a directory
479 \\conky\foo\ is a directory
480 \\conky\foo\media is a directory
481 \\conky\foo\media\ is not a directory
482
483
484cgi.py (or other CGI programming) doesn't work sometimes on NT or win95!
485------------------------------------------------------------------------
486
487Be sure you have the latest python.exe, that you are using python.exe rather
488than a GUI version of Python and that you have configured the server to execute
489::
490
491 "...\python.exe -u ..."
492
493for the CGI execution. The :option:`-u` (unbuffered) option on NT and Win95
494prevents the interpreter from altering newlines in the standard input and
495output. Without it post/multipart requests will seem to have the wrong length
496and binary (e.g. GIF) responses may get garbled (resulting in broken images, PDF
497files, and other binary downloads failing).
498
499
500Why doesn't os.popen() work in PythonWin on NT?
501-----------------------------------------------
502
503The reason that os.popen() doesn't work from within PythonWin is due to a bug in
504Microsoft's C Runtime Library (CRT). The CRT assumes you have a Win32 console
505attached to the process.
506
507You should use the win32pipe module's popen() instead which doesn't depend on
508having an attached Win32 console.
509
510Example::
511
512 import win32pipe
513 f = win32pipe.popen('dir /c c:\\')
Georg Brandl62423cb2009-12-19 17:59:59 +0000514 print(f.readlines())
Georg Brandld7413152009-10-11 21:25:26 +0000515 f.close()
516
517
518Why doesn't os.popen()/win32pipe.popen() work on Win9x?
519-------------------------------------------------------
520
521There is a bug in Win9x that prevents os.popen/win32pipe.popen* from
522working. The good news is there is a way to work around this problem. The
523Microsoft Knowledge Base article that you need to lookup is: Q150956. You will
Georg Brandl495f7b52009-10-27 15:28:25 +0000524find links to the knowledge base at: http://support.microsoft.com/.
Georg Brandld7413152009-10-11 21:25:26 +0000525
526
527PyRun_SimpleFile() crashes on Windows but not on Unix; why?
528-----------------------------------------------------------
529
530This is very sensitive to the compiler vendor, version and (perhaps) even
531options. If the FILE* structure in your embedding program isn't the same as is
532assumed by the Python interpreter it won't work.
533
534The Python 1.5.* DLLs (``python15.dll``) are all compiled with MS VC++ 5.0 and
535with multithreading-DLL options (``/MD``).
536
537If you can't change compilers or flags, try using :cfunc:`Py_RunSimpleString`.
538A trick to get it to run an arbitrary file is to construct a call to
539:func:`execfile` with the name of your file as argument.
540
541Also note that you can not mix-and-match Debug and Release versions. If you
542wish to use the Debug Multithreaded DLL, then your module *must* have an "_d"
543appended to the base name.
544
545
546Importing _tkinter fails on Windows 95/98: why?
547------------------------------------------------
548
549Sometimes, the import of _tkinter fails on Windows 95 or 98, complaining with a
550message like the following::
551
552 ImportError: DLL load failed: One of the library files needed
553 to run this application cannot be found.
554
555It could be that you haven't installed Tcl/Tk, but if you did install Tcl/Tk,
556and the Wish application works correctly, the problem may be that its installer
557didn't manage to edit the autoexec.bat file correctly. It tries to add a
558statement that changes the PATH environment variable to include the Tcl/Tk 'bin'
559subdirectory, but sometimes this edit doesn't quite work. Opening it with
560notepad usually reveals what the problem is.
561
562(One additional hint, noted by David Szafranski: you can't use long filenames
563here; e.g. use ``C:\PROGRA~1\Tcl\bin`` instead of ``C:\Program Files\Tcl\bin``.)
564
565
566How do I extract the downloaded documentation on Windows?
567---------------------------------------------------------
568
569Sometimes, when you download the documentation package to a Windows machine
570using a web browser, the file extension of the saved file ends up being .EXE.
571This is a mistake; the extension should be .TGZ.
572
573Simply rename the downloaded file to have the .TGZ extension, and WinZip will be
574able to handle it. (If your copy of WinZip doesn't, get a newer one from
575http://www.winzip.com.)
576
577
578Missing cw3215mt.dll (or missing cw3215.dll)
579--------------------------------------------
580
581Sometimes, when using Tkinter on Windows, you get an error that cw3215mt.dll or
582cw3215.dll is missing.
583
584Cause: you have an old Tcl/Tk DLL built with cygwin in your path (probably
585``C:\Windows``). You must use the Tcl/Tk DLLs from the standard Tcl/Tk
586installation (Python 1.5.2 comes with one).
587
588
589Warning about CTL3D32 version from installer
590--------------------------------------------
591
592The Python installer issues a warning like this::
593
594 This version uses ``CTL3D32.DLL`` which is not the correct version.
595 This version is used for windows NT applications only.
596
597Tim Peters:
598
599 This is a Microsoft DLL, and a notorious source of problems. The message
600 means what it says: you have the wrong version of this DLL for your operating
601 system. The Python installation did not cause this -- something else you
602 installed previous to this overwrote the DLL that came with your OS (probably
603 older shareware of some sort, but there's no way to tell now). If you search
604 for "CTL3D32" using any search engine (AltaVista, for example), you'll find
605 hundreds and hundreds of web pages complaining about the same problem with
606 all sorts of installation programs. They'll point you to ways to get the
607 correct version reinstalled on your system (since Python doesn't cause this,
608 we can't fix it).
609
610David A Burton has written a little program to fix this. Go to
Georg Brandl495f7b52009-10-27 15:28:25 +0000611http://www.burtonsys.com/downloads.html and click on "ctl3dfix.zip".