blob: 7792cfaa16a19dddb4f2a1f2346c7fd2e0637ce4 [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
26.. sidebar:: |Python Development on XP|_
27 :subtitle: `Python Development on XP`_
28
29 This series of screencasts aims to get you up and running with Python on
30 Windows XP. The knowledge is distilled into 1.5 hours and will get you up
31 and running with the right Python distribution, coding in your choice of IDE,
32 and debugging and writing solid code with unit-tests.
33
34.. |Python Development on XP| image:: python-video-icon.png
35.. _`Python Development on XP`:
Georg Brandl77fe77d2014-10-29 09:24:54 +010036 http://showmedo.com/videotutorials/series?name=pythonOzsvaldPyNewbieSeries
Georg Brandld7413152009-10-11 21:25:26 +000037
38Unless you use some sort of integrated development environment, you will end up
39*typing* Windows commands into what is variously referred to as a "DOS window"
40or "Command prompt window". Usually you can create such a window from your
Brian Curtin655b0c42012-12-16 23:58:09 -060041Start menu; under Windows 7 the menu selection is :menuselection:`Start -->
Georg Brandld7413152009-10-11 21:25:26 +000042Programs --> Accessories --> Command Prompt`. You should be able to recognize
43when you have started such a window because you will see a Windows "command
Miss Islington (bot)b5719582018-04-09 07:56:44 -070044prompt", which usually looks like this:
45
46.. code-block:: doscon
Georg Brandld7413152009-10-11 21:25:26 +000047
48 C:\>
49
50The letter may be different, and there might be other things after it, so you
Miss Islington (bot)b5719582018-04-09 07:56:44 -070051might just as easily see something like:
52
53.. code-block:: doscon
Georg Brandld7413152009-10-11 21:25:26 +000054
Brian Curtin655b0c42012-12-16 23:58:09 -060055 D:\YourName\Projects\Python>
Georg Brandld7413152009-10-11 21:25:26 +000056
57depending on how your computer has been set up and what else you have recently
58done with it. Once you have started such a window, you are well on the way to
59running Python programs.
60
61You need to realize that your Python scripts have to be processed by another
Brian Curtin655b0c42012-12-16 23:58:09 -060062program called the Python *interpreter*. The interpreter reads your script,
Georg Brandld7413152009-10-11 21:25:26 +000063compiles it into bytecodes, and then executes the bytecodes to run your
64program. So, how do you arrange for the interpreter to handle your Python?
65
66First, you need to make sure that your command window recognises the word
67"python" as an instruction to start the interpreter. If you have opened a
68command window, you should try entering the command ``python`` and hitting
Miss Islington (bot)b5719582018-04-09 07:56:44 -070069return:
70
71.. code-block:: doscon
Georg Brandld7413152009-10-11 21:25:26 +000072
Brian Curtin655b0c42012-12-16 23:58:09 -060073 C:\Users\YourName> python
74
Miss Islington (bot)b5719582018-04-09 07:56:44 -070075You should then see something like:
76
77.. code-block:: pycon
Brian Curtin655b0c42012-12-16 23:58:09 -060078
79 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 +000080 Type "help", "copyright", "credits" or "license" for more information.
81 >>>
82
83You have started the interpreter in "interactive mode". That means you can enter
84Python statements or expressions interactively and have them executed or
85evaluated while you wait. This is one of Python's strongest features. Check it
Miss Islington (bot)b5719582018-04-09 07:56:44 -070086by entering a few expressions of your choice and seeing the results:
87
88.. code-block:: pycon
Georg Brandld7413152009-10-11 21:25:26 +000089
Georg Brandl62423cb2009-12-19 17:59:59 +000090 >>> print("Hello")
Georg Brandld7413152009-10-11 21:25:26 +000091 Hello
92 >>> "Hello" * 3
Georg Brandl9205e9e2014-10-06 17:51:09 +020093 'HelloHelloHello'
Georg Brandld7413152009-10-11 21:25:26 +000094
95Many people use the interactive mode as a convenient yet highly programmable
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +030096calculator. When you want to end your interactive Python session, hold the :kbd:`Ctrl`
97key 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 +000098Windows command prompt.
99
100You may also find that you have a Start-menu entry such as :menuselection:`Start
Brian Curtin655b0c42012-12-16 23:58:09 -0600101--> Programs --> Python 3.3 --> Python (command line)` that results in you
Georg Brandld7413152009-10-11 21:25:26 +0000102seeing the ``>>>`` prompt in a new window. If so, the window will disappear
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300103after you enter the :kbd:`Ctrl-Z` character; Windows is running a single "python"
Georg Brandld7413152009-10-11 21:25:26 +0000104command in the window, and closes it when you terminate the interpreter.
105
106If the ``python`` command, instead of displaying the interpreter prompt ``>>>``,
107gives you a message like::
108
Brian Curtin655b0c42012-12-16 23:58:09 -0600109 'python' is not recognized as an internal or external command, operable program or batch file.
Georg Brandld7413152009-10-11 21:25:26 +0000110
111.. sidebar:: |Adding Python to DOS Path|_
112 :subtitle: `Adding Python to DOS Path`_
113
114 Python is not added to the DOS path by default. This screencast will walk
115 you through the steps to add the correct entry to the `System Path`, allowing
116 Python to be executed from the command-line by all users.
117
118.. |Adding Python to DOS Path| image:: python-video-icon.png
119.. _`Adding Python to DOS Path`:
Georg Brandl77fe77d2014-10-29 09:24:54 +0100120 http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96
Georg Brandld7413152009-10-11 21:25:26 +0000121
122
123or::
124
125 Bad command or filename
126
127then you need to make sure that your computer knows where to find the Python
128interpreter. To do this you will have to modify a setting called PATH, which is
129a list of directories where Windows will look for programs.
130
131You should arrange for Python's installation directory to be added to the PATH
132of every command window as it starts. If you installed Python fairly recently
133then the command ::
134
135 dir C:\py*
136
137will probably tell you where it is installed; the usual location is something
Brian Curtin655b0c42012-12-16 23:58:09 -0600138like ``C:\Python33``. Otherwise you will be reduced to a search of your whole
Georg Brandld7413152009-10-11 21:25:26 +0000139disk ... use :menuselection:`Tools --> Find` or hit the :guilabel:`Search`
140button and look for "python.exe". Supposing you discover that Python is
Brian Curtin655b0c42012-12-16 23:58:09 -0600141installed in the ``C:\Python33`` directory (the default at the time of writing),
Georg Brandld7413152009-10-11 21:25:26 +0000142you should make sure that entering the command ::
143
Brian Curtin655b0c42012-12-16 23:58:09 -0600144 c:\Python33\python
Georg Brandld7413152009-10-11 21:25:26 +0000145
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300146starts up the interpreter as above (and don't forget you'll need a ":kbd:`Ctrl-Z`" and
147an ":kbd:`Enter`" to get out of it). Once you have verified the directory, you can
Brian Curtin655b0c42012-12-16 23:58:09 -0600148add it to the system path to make it easier to start Python by just running
149the ``python`` command. This is currently an option in the installer as of
150CPython 3.3.
Georg Brandld7413152009-10-11 21:25:26 +0000151
Brian Curtin655b0c42012-12-16 23:58:09 -0600152More information about environment variables can be found on the
153:ref:`Using Python on Windows <setting-envvars>` page.
Georg Brandld7413152009-10-11 21:25:26 +0000154
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000155How do I make Python scripts executable?
Georg Brandld7413152009-10-11 21:25:26 +0000156----------------------------------------
157
Brian Curtin655b0c42012-12-16 23:58:09 -0600158On Windows, the standard Python installer already associates the .py
Georg Brandld7413152009-10-11 21:25:26 +0000159extension with a file type (Python.File) and gives that file type an open
160command that runs the interpreter (``D:\Program Files\Python\python.exe "%1"
161%*``). This is enough to make scripts executable from the command prompt as
162'foo.py'. If you'd rather be able to execute the script by simple typing 'foo'
163with no extension you need to add .py to the PATHEXT environment variable.
164
Georg Brandld7413152009-10-11 21:25:26 +0000165Why does Python sometimes take so long to start?
166------------------------------------------------
167
168Usually Python starts very quickly on Windows, but occasionally there are bug
169reports that Python suddenly begins to take a long time to start up. This is
170made even more puzzling because Python will work fine on other Windows systems
171which appear to be configured identically.
172
173The problem may be caused by a misconfiguration of virus checking software on
174the problem machine. Some virus scanners have been known to introduce startup
175overhead of two orders of magnitude when the scanner is configured to monitor
176all reads from the filesystem. Try checking the configuration of virus scanning
177software on your systems to ensure that they are indeed configured identically.
178McAfee, when configured to scan all file system read activity, is a particular
179offender.
180
181
Brian Curtin655b0c42012-12-16 23:58:09 -0600182How do I make an executable from a Python script?
183-------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000184
Sanyam Khurana1b4587a2017-12-06 22:09:33 +0530185See `cx_Freeze <https://anthony-tuininga.github.io/cx_Freeze/>`_ for a distutils extension
186that allows you to create console and GUI executables from Python code.
Zachary Ware9fc0e992014-01-17 08:59:44 -0600187`py2exe <http://www.py2exe.org/>`_, the most popular extension for building
188Python 2.x-based executables, does not yet support Python 3 but a version that
189does is in development.
190
Georg Brandld7413152009-10-11 21:25:26 +0000191
192Is a ``*.pyd`` file the same as a DLL?
193--------------------------------------
194
Georg Brandld7413152009-10-11 21:25:26 +0000195Yes, .pyd files are dll's, but there are a few differences. If you have a DLL
Zachary Ware9fc0e992014-01-17 08:59:44 -0600196named ``foo.pyd``, then it must have a function ``PyInit_foo()``. You can then
Georg Brandld7413152009-10-11 21:25:26 +0000197write Python "import foo", and Python will search for foo.pyd (as well as
Zachary Ware9fc0e992014-01-17 08:59:44 -0600198foo.py, foo.pyc) and if it finds it, will attempt to call ``PyInit_foo()`` to
Georg Brandld7413152009-10-11 21:25:26 +0000199initialize it. You do not link your .exe with foo.lib, as that would cause
200Windows to require the DLL to be present.
201
202Note that the search path for foo.pyd is PYTHONPATH, not the same as the path
203that Windows uses to search for foo.dll. Also, foo.pyd need not be present to
204run your program, whereas if you linked your program with a dll, the dll is
205required. Of course, foo.pyd is required if you want to say ``import foo``. In
206a DLL, linkage is declared in the source code with ``__declspec(dllexport)``.
207In a .pyd, linkage is defined in a list of available functions.
208
209
210How can I embed Python into a Windows application?
211--------------------------------------------------
212
213Embedding the Python interpreter in a Windows app can be summarized as follows:
214
2151. Do _not_ build Python into your .exe file directly. On Windows, Python must
216 be a DLL to handle importing modules that are themselves DLL's. (This is the
Georg Brandl4985ff22010-10-17 10:14:38 +0000217 first key undocumented fact.) Instead, link to :file:`python{NN}.dll`; it is
218 typically installed in ``C:\Windows\System``. *NN* is the Python version, a
Brian Curtin655b0c42012-12-16 23:58:09 -0600219 number such as "33" for Python 3.3.
Georg Brandld7413152009-10-11 21:25:26 +0000220
Georg Brandl4985ff22010-10-17 10:14:38 +0000221 You can link to Python in two different ways. Load-time linking means
222 linking against :file:`python{NN}.lib`, while run-time linking means linking
223 against :file:`python{NN}.dll`. (General note: :file:`python{NN}.lib` is the
Georg Brandlfc9794a2010-10-17 10:15:50 +0000224 so-called "import lib" corresponding to :file:`python{NN}.dll`. It merely
Georg Brandl4985ff22010-10-17 10:14:38 +0000225 defines symbols for the linker.)
Georg Brandld7413152009-10-11 21:25:26 +0000226
Georg Brandl4985ff22010-10-17 10:14:38 +0000227 Run-time linking greatly simplifies link options; everything happens at run
228 time. Your code must load :file:`python{NN}.dll` using the Windows
Georg Brandld7413152009-10-11 21:25:26 +0000229 ``LoadLibraryEx()`` routine. The code must also use access routines and data
230 in :file:`python{NN}.dll` (that is, Python's C API's) using pointers obtained
231 by the Windows ``GetProcAddress()`` routine. Macros can make using these
232 pointers transparent to any C code that calls routines in Python's C API.
233
234 Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe
235 first.
236
Georg Brandl4985ff22010-10-17 10:14:38 +0000237 .. XXX what about static linking?
238
Georg Brandld7413152009-10-11 21:25:26 +00002392. If you use SWIG, it is easy to create a Python "extension module" that will
240 make the app's data and methods available to Python. SWIG will handle just
241 about all the grungy details for you. The result is C code that you link
242 *into* your .exe file (!) You do _not_ have to create a DLL file, and this
243 also simplifies linking.
244
2453. SWIG will create an init function (a C function) whose name depends on the
246 name of the extension module. For example, if the name of the module is leo,
247 the init function will be called initleo(). If you use SWIG shadow classes,
248 as you should, the init function will be called initleoc(). This initializes
249 a mostly hidden helper class used by the shadow class.
250
251 The reason you can link the C code in step 2 into your .exe file is that
252 calling the initialization function is equivalent to importing the module
253 into Python! (This is the second key undocumented fact.)
254
2554. In short, you can use the following code to initialize the Python interpreter
256 with your extension module.
257
258 .. code-block:: c
259
260 #include "python.h"
261 ...
262 Py_Initialize(); // Initialize Python.
263 initmyAppc(); // Initialize (import) the helper class.
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200264 PyRun_SimpleString("import myApp"); // Import the shadow class.
Georg Brandld7413152009-10-11 21:25:26 +0000265
2665. There are two problems with Python's C API which will become apparent if you
267 use a compiler other than MSVC, the compiler used to build pythonNN.dll.
268
269 Problem 1: The so-called "Very High Level" functions that take FILE *
270 arguments will not work in a multi-compiler environment because each
271 compiler's notion of a struct FILE will be different. From an implementation
272 standpoint these are very _low_ level functions.
273
274 Problem 2: SWIG generates the following code when generating wrappers to void
275 functions:
276
277 .. code-block:: c
278
279 Py_INCREF(Py_None);
280 _resultobj = Py_None;
281 return _resultobj;
282
283 Alas, Py_None is a macro that expands to a reference to a complex data
284 structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will
285 fail in a mult-compiler environment. Replace such code by:
286
287 .. code-block:: c
288
289 return Py_BuildValue("");
290
291 It may be possible to use SWIG's ``%typemap`` command to make the change
292 automatically, though I have not been able to get this to work (I'm a
293 complete SWIG newbie).
294
2956. Using a Python shell script to put up a Python interpreter window from inside
296 your Windows app is not a good idea; the resulting window will be independent
297 of your app's windowing system. Rather, you (or the wxPythonWindow class)
298 should create a "native" interpreter window. It is easy to connect that
299 window to the Python interpreter. You can redirect Python's i/o to _any_
300 object that supports read and write, so all you need is a Python object
301 (defined in your extension module) that contains read() and write() methods.
302
Georg Brandld7413152009-10-11 21:25:26 +0000303How do I keep editors from inserting tabs into my Python source?
304----------------------------------------------------------------
305
306The FAQ does not recommend using tabs, and the Python style guide, :pep:`8`,
307recommends 4 spaces for distributed Python code; this is also the Emacs
308python-mode default.
309
310Under any editor, mixing tabs and spaces is a bad idea. MSVC is no different in
311this respect, and is easily configured to use spaces: Take :menuselection:`Tools
312--> Options --> Tabs`, and for file type "Default" set "Tab size" and "Indent
313size" to 4, and select the "Insert spaces" radio button.
314
Victor Stinner2b501862017-02-13 15:30:05 +0100315Python raises :exc:`IndentationError` or :exc:`TabError` if mixed tabs
Jim DeLaHunt3d707be2017-02-13 05:57:13 -0800316and spaces are causing problems in leading whitespace.
Victor Stinner2b501862017-02-13 15:30:05 +0100317You may also run the :mod:`tabnanny` module to check a directory tree
Jim DeLaHunt3d707be2017-02-13 05:57:13 -0800318in batch mode.
Georg Brandld7413152009-10-11 21:25:26 +0000319
320
321How do I check for a keypress without blocking?
322-----------------------------------------------
323
324Use the msvcrt module. This is a standard Windows-specific extension module.
325It defines a function ``kbhit()`` which checks whether a keyboard hit is
326present, and ``getch()`` which gets one character without echoing it.
327
328
329How do I emulate os.kill() in Windows?
330--------------------------------------
331
Miss Islington (bot)b5719582018-04-09 07:56:44 -0700332Prior to Python 2.7 and 3.2, to terminate a process, you can use :mod:`ctypes`:
333
334.. code-block:: python
Georg Brandlff24c8e2010-03-21 09:52:24 +0000335
336 import ctypes
Georg Brandld7413152009-10-11 21:25:26 +0000337
338 def kill(pid):
339 """kill function for Win32"""
Georg Brandlff24c8e2010-03-21 09:52:24 +0000340 kernel32 = ctypes.windll.kernel32
341 handle = kernel32.OpenProcess(1, 0, pid)
342 return (0 != kernel32.TerminateProcess(handle, 0))
Georg Brandld7413152009-10-11 21:25:26 +0000343
Brian Curtinf4ed2062010-04-12 18:10:10 +0000344In 2.7 and 3.2, :func:`os.kill` is implemented similar to the above function,
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300345with the additional feature of being able to send :kbd:`Ctrl+C` and :kbd:`Ctrl+Break`
Brian Curtinf4ed2062010-04-12 18:10:10 +0000346to console subprocesses which are designed to handle those signals. See
347:func:`os.kill` for further details.
348
Georg Brandld7413152009-10-11 21:25:26 +0000349How do I extract the downloaded documentation on Windows?
350---------------------------------------------------------
351
352Sometimes, when you download the documentation package to a Windows machine
353using a web browser, the file extension of the saved file ends up being .EXE.
354This is a mistake; the extension should be .TGZ.
355
356Simply rename the downloaded file to have the .TGZ extension, and WinZip will be
357able to handle it. (If your copy of WinZip doesn't, get a newer one from
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300358https://www.winzip.com.)
Georg Brandld7413152009-10-11 21:25:26 +0000359