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