In this chapter we look at two integrated development environments (IDEs) for Python on Windows:
?PythonWin provides IDE capabilities for Python on Windows. It has a number of features in its environment that make editing and debugging Python code more pleasant and productive than standard text editors. Because the IDE features are part of the PythonWin package, you can take advantage of them if you develop your GUI application using PythonWin or if you extend your existing C++ MFC application by embedding PythonWin. More detail on the PythonWin framework can be found in Chapter 20, GUI Development.
?IDLE is an IDE developed by Python author, Guido van Rossum. IDLE uses the Tkinter GUI framework and is portable to all Python platforms with Tkinter support. IDLE is a standalone IDE for Python; it doesn't attempt to provide a GUI or application framework. IDLE would be particularly suitable if you develop your GUI applications using Tkinter or regularly use Python on operating systems other than Windows. Guido has kindly assisted in the section of this chapter devoted to IDLE.
PythonWin is many things. As we discuss in Chapter 20, one of PythonWin's major roles is to be a Python interface to the Microsoft Foundation Classes, allowing an application to take advantage of some of the more esoteric user interface features available on Windows.
PythonWin is almost a sample application for these MFC extensions. Over time, it has slowly developed features that make it useful as an IDE. As time goes on, we can except these features to improve.
When PythonWin starts, it automatically opens its Interactive Window, where you see the Python copyright message and the standard Python prompt:
If you are familiar with Python on any other operating system or have used the standard Python.exe included with the Python distribution, you can immediately start entering Python commands to be executed interactively. Chapter 2, Python Language Review, and the Python tutorial (optionally installed with the Python distribution), describes using Python interactively, and we discuss some additional PythonWin features later in this chapter.
As much as possible, PythonWin conforms to the standard user-interface features of Windows. Thus, you will notice a Windows toolbar with familiar File ® Open and File ® New icons, and a fairly standard set of menus at the top of the application. Most of the items on the menus are obvious, so we won't describe the exact operation of the File ® Open and File ® New operations. Instead, we will focus on the features specific to PythonWin.
Now would be a good time to create a new Python source file to demonstrate some of the features of PythonWin. To create a new file, select the blank document toolbar item, then select File ® New or press Ctrl-N. A dialog box appears that asks which type of document to create. Select Python Script.
A blank source file is created. Type the following code:
print "Hello, " + msg
print "Script name is", sys.argv
hello("Please say something next time")
As you type, notice the first feature: Python syntax coloring. If you don't like the particular styles, they can be changed via the View ® Options menu. Now save the file as pywindemo.py in a convenient directory, and you're ready to begin.
PythonWin allows you to run arbitrary scripts from within its environment. Changes to the file are saved before the script is run. You can execute a script by selecting the ''running man'' toolbar button, and then select File ® Run, or press Ctrl-R.
Let's run the script we just created. When you select this option, the PythonWin environment should look something like Figure 4-1.
PythonWin's Run Script dialog
For now, ignore the debugger, so you can leave everything with its default values and select OK.
You should see the following message output to the interactive window:
Script name is c:\scripts\pywindemo.py
Hello, Please say something next time
Notice that the script is run the same way you executed python.exe pywindemo.py. The if __name__==慱_main__?/TT>: block is entered, and sys.argv is used to obtain the command-line parameters. If you perform this procedure again, you can experiment with adding command-line arguments in the Run dialog.
A handy feature to note is that if you hold down the Shift key while running the module (i.e., while clicking the toolbar or by pressing Ctrl-Shift-R), the code runs without displaying the dialog. This is handy for repeatedly running the same script with the same arguments.
Importing modules in the PythonWin environment is similar to running Python scripts; they both execute Python code. However, there is an important distinction between importing modules and running scripts.
Importing the module pywindemo.py operates almost identically to typing the Python statement:
>>> import pywindemo
When a module is imported this way, the if __name__==慱_main__?/TT>: block isn't entered, but the name of the script is entered into the Python namespace.
There are two important differences between the PythonWin import functionality and simply typing import pywindemo. First, the file is saved; and second, PythonWin automatically performs a reload() of the module if necessary. These features combine to ensure the latest version of the code is made available.
You can import a module in PythonWin by selecting the Import toolbar icon, and selecting File ® Import or pressing Ctrl-I. If an editor window has the focus, that module is imported; otherwise, a dialog is opened allowing you to select the Python module to be imported.
Let's import the test module. Make sure it's the foreground window and press Ctrl-I. The status bar displays the message Successfully imported the module 憄ywindemo?/TT>, and no message is printed to the interactive window. So although the module is imported, the if __name__==慱_main__?/TT>: block isn't executed.
Now that you've imported the module, you can use it as you would any Python module. Go to the Interactive Window and type:
>>> pywindemo.hello("how are you")
Hello, how are you
Importing modules is primarily useful when developing or debugging a fairly large application under PythonWin. For example, let's assume you have the following code structure:
# module spam1
And another similar module:
# module spam2
If you find a bug in the spamutil module, you can edit it in PythonWin, then import the module. The spam1 and spam2 modules will then also be working with the new version of spamutil.
PythonWin includes a function that allows you to check a Python source file without executing it. The syntax of the source code is checked using Python itself, while the Python tabnanny tool checks the source-code whitespace. Any syntax or whitespace errors are reported in the PythonWin status bar.
You can check a module by selecting the Check Module toolbar item, then selecting File ® Check or pressing Ctrl-C.
To assist in locating your Python source files, PythonWin can look down the Python sys.path for a file.
To locate a Python file, select File ® Locate or press Ctrl-L. A dialog is displayed asking for the name of a module to locate.
If you enter string into this dialog, PythonWin searches the path for a module named string.py. PythonWin should locate and open the standard Python string module.
This feature is aware of Python packages. You could enter a module name of pywin.framework.app to locate the PythonWin application module in the file pywin\framework\app.py.
PythonWin supports a number of command-line parameters as shown in this table.
By default, PythonWin allows only one instance to be open. If you attempt to start a new instance of PythonWin, the existing instance is reused, primarily to support better integration with Windows Explorer, as described later in this chapter. PythonWin uses Dynamic Data Exchange (DDE) to communicate between instances, so the /nodde parameter can disable this behavior and allow as many PythonWin instances as you care to start.
To demonstrate these command lines, close the source file pywindemo.py (leave PythonWin running) and start a command prompt window. Enter the command:
C:\Somewhere> start pythonwin.exe /edit C:\Scripts\pywindemo.py
You should see your existing PythonWin application come to the foreground, and see pywindemo.py opened for editing. Switch back to the command prompt and enter the command:
C:\Somewhere> start pythonwin.exe /run c:\Scripts\pywindemo.py
You should see the same messages printed as when you ran the script directly from PythonWin. Finally, from the command prompt enter:
C:\Somewhere> start pythonwin.exe /nodde /edit c:\scripts\pywindemo.py
And a new instance of PythonWin starts, with its own copy of pywindemo.py open for editing.
At the most obvious level, the PythonWin interactive window simulates the built-in Python interpreter in interactive mode. Almost anything you type in the standard Python shell can be used in PythonWin.
To reexecute blocks of code you previously executed, scroll the cursor to the old block and press Enter. The block is copied to the end of the interactive window, allowing you to make any changes before finally reexecuting the code. Alternatively, the Ctrl-Up and Ctrl-Down keys allow you to scroll through the previously executed commands.
PythonWin can also help you locate the source of errors in standard Python trace-backs. All Python tracebacks are printed to the interactive window, and you can double-click (or press Enter) on any line in a traceback to open the offending line in the editor.
As an example, let's force an error in our test script. Open the same pywindemo.py created earlier and select File ® Import. Now close the source file. In the interactive window, type:
PythonWin responds with:
Traceback (innermost last):
File "<interactive input>", line 0, in ?
File "c:\scripts\pywindemo.py", line 2, in hello
print "Hello, " + msg
TypeError: illegal argument type for built-in operation
If you double-click on the third or fourth lines of this traceback, the test script is opened, and you are at line 2, the line with the indicated error.
The PythonWin editor has many features especially designed for Python programs. In many cases these features are shared between IDLE and PythonWin; both IDEs use exactly the same (Python!) code to implement the same features.* The most important features with a brief description are provided here:
Unlimited undo and redo capabilities
The editor examines existing source files to determine their indentation. If configured, the editor can override your tab preferences to match the existing file. When indenting an incomplete expression (such as a multiline list definition or function call), the correct indentation is applied to line up elements in the list or the call parameters. Entire blocks can be indented or not to allow easy program restructuring.
You can select a block of text and have it all commented or not with a single command.
Comment and multiline string formatting
Comment blocks and multiline strings can be reformatted. This command correctly reformats paragraphs to a 70-character width.
If you type the name of a module and certain other objects, then press the period key, a list box is displayed with a selection of attributes. The arrow keys allow you to change the selection, and the Tab key selects it. You can see this by typing string. in an editor or interactive window. As this book goes to press, this feature had not yet been ported to IDLE.
|* And truth be told, PythonWin stole most of these features after IDLE had already implemented them. No point reinventing the wheel!|
As you type the name of a Python function and open the parenthesis, a popup window with information about the function may be displayed. The easiest way to see this in action is to type string.split (, and the Call Tip window should display.
This is a handy feature that means you need never mistype a variable name again. You can type the start of any word and press the ALT-/ key to complete the word. The current file is searched for words, and all words that match are selected. For example, let's assume you have an editor window with the code:
strval = string.join(["hi", "there"])
If you type st and press ALT-/, string is substituted. If you press it again, strval is substituted, and so forth.
As whitespace is significant in Python, there is an option in PythonWin that allows you to view the whitespace in your file. Space characters are shown as a soft dot; tab characters are shown as an arrow. IDLE doesn't support this feature.
Fixed and proportional fonts
Many people prefer to use proportional fonts to edit source code, but proportional fonts often make it hard to see if your source code is correctly aligned. PythonWin allows you to choose your preferred fixed and proportional font and quickly toggle between the two.
Integrated object browser
Each editor window in PythonWin has an integrated browser window. This window is initially closed, but can be shown by selecting the splitter bar on the left side of the window. This browser allows you to see all the classes and functions defined in the current source file and quickly move between them.
The Ctrl-F2 key allows you to set a bookmark at any line in a source file. Pressing F2 moves you between bookmarks defined in the current file. A bookmark is indicated in the margin of the editor window. Bookmarks are not available in IDLE.
Automatic file backup
PythonWin can be configured to save backup copies of your source files. These backups can be saved either in the same directory as the original but with the file extensions changed to .bak, or with the same name into a bak subdirectory in your Windows temp directory.
Available from the Tools menu, the Python path browser is really a bit of a misnomer. When you open the browser, it does indeed display each directory on your PythonPath and each module in that directory. However, the browser also allows you to delve into the modules, examining the functions and classes defined within.
PythonWin supports a fairly simple object browser. This allows you to peer deep inside any Python object, allowing you to discover various details about the object.
In contrast with the Python path browser, the object browser doesn't browse Python source code: only Python objects. This means that objects you wish to browse must actually exist in the Python environment. For example, the only way to browse a Python module in this browser is to import the module.
The object browser can be found by selecting Tools ® Browser or by pressing Ctrl-B. A dialog is presented asking for the object to browse; to browse the sample Python module, enter pywindemo and select OK.
If you expand the hello() function in the browser, you should have a window similar to that shown in Figure 4-2.
The PythonWin browser
Because the browser digs deeply into Python's internals, some of the information presented is quite esoteric. However, it can often provide useful information about your objects.
PythonWin provides basic integration with the Windows Explorer. All .py and .pyw files shown in the Windows Explorer have an Edit option on their context (i.e., right-click) menu. Selecting this option starts PythonWin if it isn't already running, and opens the file for editing.
You can also drag and drop files from the Windows Explorer into PythonWin. These files are also open for editing.
PythonWin has also been registered with Windows in such a way that it can be run without knowing its specific location and without having it on your system path. If you select Start ® Run from the Windows taskbar and enter pythonwin, it's correctly located and started. From a command prompt, you can also execute the command start pythonwin from any directory, and PythonWin starts. See the previous section, "Command-Line Parameters."
PythonWin also has a built-in Python debugger to help you develop your scripts. The PythonWin debugger includes all the features you expect in debuggers, including:
?Breakpoints that can be set at any location. Optionally, these breakpoints may have a condition that must evaluate to true before the breakpoint stops.
?A watch window allowing easy tracking of changes to key variables.
?Commands allowing you to step into, over, or out of functions.
If you are familiar with other Windows IDE debugging environments (such as Visual C++, Visual Basic, or Delphi) you should find the debugger easy to work with.
For a language as flexible as Python, there is one huge limitation in the debugger that is worth noting. It isn't possible to modify the code while it's being debugged. If you spot a bug while debugging, code changes you make aren't applied until you reload the module. Further, any source-code changes are likely to disrupt the debugging session, as the debugger will still be stepping though the original line positions even though they are likely to have changed.
The simplest way to use the debugger is to run scripts using the same technique described earlier, but this time select one of the debugging options. The Run Script dialog provides the following debugging options:
This means that the script runs normally without any debugging; it doesn't stop at breakpoints.
Step through in the debugger
Steps through each line in the debugger. Selecting this option invokes the debugger at the first line in our script. The default PythonWin configuration binds the F11 (step in) or F10 (step over) keys to this function.
Run in the debugger
Runs the script under the debugger, stopping only at breakpoints. If you select this option when no breakpoints are set, PythonWin warns you that the debugger is unlikely to be invoked. Of course, PythonWin can't determine if your breakpoints are on lines that are actually executed. If none of your breakpoints are actually hit, this command appears to run without the debugger at all; the script starts and completes normally (albeit slightly slower due to the debugger overhead). The default PythonWin configuration binds the F5 key (Go) to this function.
Postmortem of unhandled exceptions
The script isn't run under the debugger, but if an unhandled exception occurs, the debugger is invoked to perform postmortem analysis. This can be handy, as it can show you the complete state of your Python program, including all variable values, at the point where the exception was raised. If your script runs successfully (i.e., doesn't generate a traceback while running), this option has no effect.
The following discussion demonstrates the debugger using the same script developed earlier in this chapter. For the example, set a breakpoint at the first line of the main() function. You can set a breakpoint by moving to the line where the breakpoint should be applied and either display the debugging toolbar (View ® Toolbars ® Debugging) and selecting the appropriate button or press the F9 key. PythonWin should respond by placing a breakpoint indicator in the margin of the editor window. The breakpoint is simply a black outline as shown in Figure 4-3, to indicate the breakpoint is currently disabled (the debugger isn't yet running).
Select the OK button, and if all goes well, the PythonWin debugger kicks in, and you will be stopped at your breakpoint. Notice a number of changes to the PythonWin environment, as shown in Figure 4-4. The most obvious are:
?A new Debugging toolbar appears, giving access to debugger-related features (this toolbar can always be displayed using View ® Toolbars ® Debugging).
?A few new debugging windows appear. These windows can be docked in the PythonWin frame or left floating. Figure 4-4 shows the Stack window docked on the left side of PythonWin, and the Breakpoints and Watch windows floating.
?The debugger breakpoint turns red, indicating the debugger is active.
Python Win about to debug our sample script
?The Interactive Window shows a [Dbg] indicator before the standard >>> and ?/TT> prompts, indicating that expressions you enter will be evaluated under the debugger's current context rather than in the global context used by default. This means you can view or change any local or global variables in the debugger's current function.
At this point, you can experiment with some of the debugger windows and use the debugger toolbar (or the keyboard shortcuts) to step through the program. Figure 4-4 shows the debugger after stopping at the breakpoint and selecting the Step command once.
The term hard breakpoint refers to the process of changing your source code to explicitly invoke the debugger. You add a line of code that invokes the debugger directly, regardless of how you are running the script. These breakpoints are called hard because they can't be removed by the debugger: they are embedded in your code, and there is no way to reset them other than again changing the code!
Python Win debugging our sample script
Hard breakpoints are particularly useful when you are unable or would find it difficult to run your scripts under PythonWin. You can add a hard breakpoint to almost any Python program, be it a PythonWin program or even a Python COM object running under Active Server Pages or Internet Explorer. In almost all cases, the PythonWin debugger environment will start up, and you can debug to your heart's content.
You can set a hard breakpoint by calling the function pywin.debugger.brk(). It's likely that you will need to import the pywin.debugger module before making the call, so the code to invoke the debugger typically looks like:
The PythonWin debugger is installed with thorough documentation, including a tutorial and sample code that demonstrates these techniques. You should familiarize yourself with this documentation to discover other debugger features.
IDLE is an alternative Integrated Development Environment for Python. By default, the Python 1.5.2 and later installations install IDLE and a shortcut to start IDLE on your Start menu.
''IDLE'' is a twist on the standard IDE acronym and is also named after Eric Idle, one of the sillier members of the Monty Python comedy troupe, but don't tell him.
As we have discussed, many IDE functions are shared between PythonWin and IDLE (or more correctly, stolen from IDLE by PythonWin, with Guido's blessing). So the differences between PythonWin and IDLE have less to do with features and more to do with platforms.
IDLE runs on almost all platforms that support Python. Although the user interface it provides isn't quite as slick as PythonWin's, you do have an IDE that runs places other than Windows. For many people, this is the single killer feature!
Of course, your choice of environment is up to you, but it appears that people who use Python on multiple platforms prefer IDLE because their environment can follow them. People who use Python only on Windows typically prefer PythonWin and its interface. As IDLE evolves further and the Tkinter GUI framework offers more features on Windows, we may find this simple distinction blurring. We recommend you spend time with both IDE environments and choose for yourself.
IDLE is itself written in Python, using Tkinter, Python's de facto cross-platform GUI package based on Tcl/Tk. Because Python and Tcl/Tk are cross platform, so is IDLE; it works as well on Windows (95, 98, NT) as on Unix (including Linux), with minor, unavoidable differences because of inherent differences between the platforms. It also works on Macintosh (although occasionally you may experience a slight problem, because this platform gets less testing).
This section describes IDLE Version 0.5, which hasn't been released at the time of writing. The Python 1.5.2 distribution comes with IDLE Version 0.4, which differs in a number of details, so these will be detailed where appropriate. In any case, IDLE requires Python 1.5.2 or later to run. Tcl/Tk 8.0 or later (optionally installed with Python 1.5.2) is needed.
As the version number should imply, IDLE is still a young application, and features are developing at a great rate. Check the online documentation regularly to keep up with the current feature set.
When IDLE starts, it presents its shell window. This window is equivalent to PythonWin's Interactive Window or the interactive Python session, and it's where you enter arbitrary Python commands.
By now, you should be completely familiar with Python's own interactive (command-line) mode. We first discussed this in Chapter 2, and also previously in this chapter, so you already know how to use IDLE's Python shell window! Figure 4-5 shows the Python shell window with a few interactive commands.
IDLE's shell window on Windows
Since we made a big song-and-dance about the cross-platform capabilities of IDLE, Figure 4-6 shows the Python shell window running on a Unix system. You will probably notice some subtle differences between the two windows; the fonts are different, hence the slightly different window sizes: the default is 80 × 24 character cells on all platforms. You may also notice that on Windows the Help menu is placed next to the other menus, while on Unix it's placed to the far right of the menu bar.
One of the first things the astute reader might query is the lack of the ?prompt in multiline statements. Using the "official" interactive Python mode or PythonWin, multiline statements normally look like:
>>> while x < 10:
?nbsp; x = x + 1
?nbsp; print x, x**3
IDLE's shell window on Unix
IDLE takes a different approach. Instead of showing secondary prompts, Python automatically indents these lines with whitespace, just like the regular editor. This is one feature not provided by PythonWin; although the interactive window does perform some smart indentation, it doesn't offer the full-blown smart indentation used by IDLE and the PythonWin editor.
Just like PythonWin, you can move to a previous command and press Enter to copy the command to the end of the buffer, ready for subsequent editing and execution. The shell window also provides history capabilities, allowing you to quickly recall next and previous commands, activated by the ALT-N and ALT-P keys, respectively.
You can use IDLE as an ordinary text editor to write Python programs. As discussed previously in this chapter, PythonWin recently adopted many of IDLE's best editor features, so the same, rich, Python-aware editing environment is available in IDLE. It's worth noting that IDLE and PythonWin have different default keyboard bindings, so the same features may be accessed in different ways; check the IDLE menus for the shortcut keys.
IDLE also colors the text of your program according to syntactic categories. For example, strings are displayed in green, so when you forget a string quote, you will probably notice before you run the program. Other editors have this feature.
and some support Python's syntax, but not many (not even Emacs) get it right at all times. The inaccuracy can be annoying, especially when you are editing multiline string literals. IDLE boasts that it gets the coloring 100% right, but you wouldn't expect any less from a Python source-code editor written in Python!
IDLE supports a Python path and Python class browser by selecting the appropriate entry from the File menu. These browsers look remarkably similar to the equivalent browsers in PythonWin, which should come as no surprise, as both IDLE and PythonWin use the standard Python module pyclbr to obtain their functionality.
As with PythonWin, IDLE supports the concept of running and importing scripts. To run or import a script, the file must be opened in the text editor and Edit ® Run Script or Edit ® Import Module selected.
These features work the same as under PythonWin. Since we have experimented with these functions using PythonWin, we won't bore you with a repeat for IDLE. However, you may still want to open the same sample script used for PythonWin and test the features using IDLE.
If a traceback is printed to the Python shell window, you can move the cursor to one of the error lines and select the Go to file/line option (from the Debug or right-click menus) to open the file.
As you expect of an IDE, IDLE contains a built-in debugger. To use the debugger, it must first be enabled via the Debug ® Debugger command from the Python shell window. The debugger dialog appears, and the shell window responds with:
IDLE is now ready to debug. To start the debugger, open the script to debug and run (or import) it. For the purposes of this example, let's debug the same script you used for PythonWin (C:\Scripts\pywindemo.py in the example). Once the file is open, select Edit ® Run script (or press Ctrl-F5). The debugger dialog becomes active, and the debugging session begins. Figure 4-7 shows you stopped inside your main function.
The stack leading to the current call is shown. Selecting an entry displays the local and global variables and the source code for the stack entry, depending on the options selected at the top of the dialog
At the time of writing, there are a few limitations in the IDLE debugger worth mentioning:
?When debugging the top-level of a module, the Go and Over commands function like the Step command. Go and Over don't function correctly until the top-level script calls a function.
?The Python shell window is effectively disabled during the debugging session. You can't use normal Python commands to view and change variables while the debugger is active.
It's quite possible that these and other limitations will be removed by the time you install IDLE.
IDLE supports postmortem debugging, which allows you to capture the state of a Python program after an exception. Unlike PythonWin, where postmortem debugging must be explicitly enabled when running a script, IDLE allows you to perform this analysis at any time directly after an unhandled exception has occurred. To perform postmortem debugging, select Debug ® Stack Viewer after the traceback has been printed. The debugger dialog is then activated, allowing you to view the state of each stack entry in the traceback.
This chapter provided a look at two IDEs available for Python on Windows. Both IDLE and PythonWin allow you to develop, run, and debug Python programs, and provide unique Python-based features you won't find in other environments.
PythonWin and IDLE are not competitors; in fact, they can be viewed as partners. The developers of both packages have gone to considerable effort to ensure that the best features of each are available in the other. As we have seen, the primary difference is the GUI environment in which they run. PythonWin runs only under Windows, and it takes full advantage of Windows features: excellent if you use only Windows. IDLE provides the one key feature PythonWin will almost certainly never have: its runs on all popular, modern operating systems.
Hopefully this chapter has allowed you to see how each development environment operates and encouraged you to try both. Although most examples in this book use PythonWin to run sample programs, they all work perfectly under IDLE, so feel to use the environment of your choice.