Text
stringlengths
1
9.41k
Use the File menu to begin (New Window) or change (Open...) a source file; use the text_ _edit window’s Run menu to run the code in that window (Run Module)._ #IDLE is a Python program that uses the standard library’s tkinter GUI toolkit (a.k.a.
Tkinter in Python 2.6) to build the IDLE GUI. This makes IDLE portable, but it also means that you’ll need to have tkinter support in your Python to use IDLE.
The Windows version of Python has this by default, but some Linux and Unix users may need to install the appropriate tkinter support (a yum tkinter command may suffice on some Linux distributions, but see the installation hints in Appendix A for details).
Mac OS X may have everything you need preinstalled, too; look for an idle command or script on your machine. **f** **|** ----- IDLE uses familiar menus with keyboard shortcuts for most of its operations.
To make (or edit) a source code file under IDLE, open a text edit window: in the main window, select the File pull-down menu, and pick New Window (or Open...
to open a text edit window displaying an existing file for editing). Although it may not show up fully in this book’s graphics, IDLE uses syntax-directed _colorization for the code typed in both the main window and all text edit windows—_ keywords are one color, literals are another, and so on.
This helps give you a better picture of the components in your code (and can even help you spot mistakes— run-on strings are all one color, for example). To run a file of code that you are editing in IDLE, select the file’s text edit window, open that window’s Run pull-down menu, and choose the Run Module option liste...
Python will let you know that you need to save your file first if you’ve changed it since it was opened or last saved and forgot to save your changes—a common mistake when you’re knee deep in coding. When run this way, the output of your script and any error messages it may generate show up back in the main interactiv...
In Figure 3-3, for example, the three lines after the “RESTART” line near the middle of the window reflect an execution of our script1.py file opened in a separate edit window. The “RESTART” message tells us that the user-code process was restarted to run the edited script and serves to separate script output (it does ...
Your prior commands will be recalled and displayed, and may be edited and rerun.
You can also recall commands by positioning the cursor on them, or use cut-and-paste operations, but these techniques tend to involve more work.
Outside IDLE, you may be able to recall commands in an interactive session with the arrow keys on Windows. ###### Using IDLE IDLE is free, easy to use, portable, and automatically available on most platforms.
I generally recommend it to Python newcomers because it sugarcoats some of the details and does not assume prior experience with system command lines.
However, it is somewhat limited compared to more advanced commercial IDEs.
To help you avoid some common pitfalls, here is a list of issues that IDLE beginners should bear in mind: - You must add “.py” explicitly when saving your files.
I mentioned this when talking about files in general, but it’s a common IDLE stumbling block, especially **|** ----- for Windows users.
IDLE does not automatically add a .py extension to filenames when files are saved. Be careful to type the .py extension yourself when saving a file for the first time.
If you don’t, while you will be able to run your file from IDLE (and system command lines), you will not be able to import it either interactively or from other modules. - Run scripts by selecting Run→Run Module in text edit windows, not by in**teractive imports and reloads.
Earlier in this chapter, we saw that it’s possible** to run a file by importing it interactively. However, this scheme can grow complex because it requires you to manually reload files after changes.
By contrast, using the Run→Run Module menu option in IDLE always runs the most current version of your file, just like running it using a system shell command line.
IDLE also prompts you to save your file first, if needed (another common mistake outside IDLE). - You need to reload only modules being tested interactively.
Like system shell command lines, IDLE’s Run→Run Module menu option always runs the current version of both the top-level file and any modules it imports.
Because of this, Run→Run Module eliminates common confusions surrounding imports.
You only need to reload modules that you are importing and testing interactively in IDLE. If you choose to use the import and reload technique instead of Run→Run Module, remember that you can use the Alt-P/Alt-N key combinations to recall prior commands. - You can customize IDLE.
To change the text fonts and colors in IDLE, select the Configure option in the Options menu of any IDLE window.
You can also customize key combination actions, indentation settings, and more; see IDLE’s Help pull-down menu for more hints. - There is currently no clear-screen option in IDLE.
This seems to be a frequent request (perhaps because it’s an option available in similar IDEs), and it might be added eventually. Today, though, there is no way to clear the interactive window’s text.
If you want the window’s text to go away, you can either press and hold the Enter key, or type a Python loop to print a series of blank lines (nobody really uses the latter technique, of course, but it sounds more high-tech than pressing the Enter key!). - tkinter GUI and threaded programs may not work well with IDLE.
Because IDLE is a Python/tkinter program, it can hang if you use it to run certain types of advanced Python/tkinter programs.
This has become less of an issue in more recent versions of IDLE that run user code in one process and the IDLE GUI itself in another, but some programs (especially those that use multithreading) might still hang the GUI.
Your code may not exhibit such problems, but as a rule of thumb, it’s always safe to use IDLE to edit GUI programs but launch them using other options, such as icon clicks or system command lines.
When in doubt, if your code fails in IDLE, try it outside the GUI. **f** **|** ----- - If connection errors arise, try starting IDLE in single-process mode.
Because IDLE requires communication between its separate user and GUI processes, it can sometimes have trouble starting up on certain platforms (notably, it fails to start occasionally on some Windows machines, due to firewall software that blocks connections).
If you run into such connection errors, it’s always possible to start IDLE with a system command line that forces it to run in single-process mode without a user-code subprocess and therefore avoids communication issues: its ``` -n command-line flag forces this mode.
On Windows, for example, start a Com ``` mand Prompt window and run the system command line idle.py -n from within the directory C:\Python30\Lib\idlelib (cd there first if needed). - Beware of some IDLE usability features.
IDLE does much to make life easier for beginners, but some of its tricks won’t apply outside the IDLE GUI.
For instance, IDLE runs your scripts in its own interactive namespace, so variables in your code show up automatically in the IDLE interactive session—you don’t always need to run import commands to access names at the top level of files you’ve already run.
This can be handy, but it can also be confusing, because outside the IDLE environment names must always be imported from files to be used. IDLE also automatically changes both to the directory of a file just run and adds its directory to the module import search path—a handy feature that allows you to import files ther...
It’s OK to use such features, but don’t forget that they are IDLE behavior, not Python behavior. ###### Advanced IDLE Tools Besides the basic edit and run functions, IDLE provides more advanced features, including a point-and-click program debugger and an object browser.
The IDLE debugger is enabled via the Debug menu and the object browser via the File menu.
The browser allows you to navigate through the module search path to files and objects in files; clicking on a file or object opens the corresponding source in a text edit window. IDLE debugging is initiated by selecting the Debug→Debugger menu option in the main window and then starting your script by selecting the R...
You can also watch program execution when debugging—the current line of code is noted as you step through your code. For simpler debugging operations, you can also right-click with your mouse on the text of an error message to quickly jump to the line of code where the error occurred—a trick that makes it simple and f...
In addition, IDLE’s text editor offers a large collection of programmer-friendly tools, including automatic indentation, advanced text and file search operations, and more.
Because IDLE uses **|** ----- intuitive GUI interactions, you should experiment with the system live to get a feel for its other tools. ###### Other IDEs Because IDLE is free, portable, and a standard part of Python, it’s a nice first development tool to become familiar with if you want to use an IDE at all.
Again, I recommend that you use IDLE for this book’s exercises if you’re just starting out, unless you are already familiar with and prefer a command-line-based development mode.
There are, however, a handful of alternative IDEs for Python developers, some of which are substantially more powerful and robust than IDLE.
Here are some of the most commonly used IDEs: _Eclipse and PyDev_ Eclipse is an advanced open source IDE GUI.
Originally developed as a Java IDE, Eclipse also supports Python development when you install the PyDev (or a similar) plug-in.
Eclipse is a popular and powerful option for Python development, and it goes well beyond IDLE’s feature set.
It includes support for code completion, syntax highlighting, syntax analysis, refactoring, debugging, and more.
Its downsides are that it is a large system to install and may require shareware extensions for some features (this may vary over time).
Still, when you are ready to graduate from IDLE, the Eclipse/PyDev combination is worth your attention. _Komodo_ A full-featured development environment GUI for Python (and other languages), Komodo includes standard syntax-coloring, text-editing, debugging, and other features.
In addition, Komodo offers many advanced features that IDLE does not, including project files, source-control integration, regular-expression debugging, and a drag-and-drop GUI builder that generates Python/tkinter code to implement the GUIs you design interactively.
At this writing, Komodo is not free; it is available at http://www.activestate.com. _NetBeans IDE for Python_ NetBeans is a powerful open-source development environment GUI with support for many advanced features for Python developers: code completion, automatic indentation and code colorization, editor hints, code fol...
It may be used to develop both CPython and Jython code. Like Eclipse, NetBeans requires installation steps beyond those of the included IDLE GUI, but it is seen by many as more than worth the effort.
Search the Web for the latest information and links. _PythonWin_ PythonWin is a free Windows-only IDE for Python that ships as part of ActiveState’s ActivePython distribution (and may also be fetched separately from http:// _www.python.org resources).
It is roughly like IDLE, with a handful of useful_ Windows-specific extensions added; for example, PythonWin has support for **|** ----- COM objects.
Today, IDLE is probably more advanced than PythonWin (for instance, IDLE’s dual-process architecture often prevents it from hanging).
However, PythonWin still offers tools for Windows developers that IDLE does not.
See http: _//www.activestate.com for more information._ _Others_ There are roughly half a dozen other widely used IDEs that I’m aware of (including the commercial Wing IDE and PythonCard) but do not have space to do justice to here, and more will probably appear over time.
In fact, almost every programmerfriendly text editor has some sort of support for Python development these days, whether it be preinstalled or fetched separately.
Emacs and Vim, for instance, have substantial Python support. I won’t try to document all such options here; for more information, see the resources available at http://www.python.org or search the Web for “Python IDE.” You might also try running a web search for “Python editors”—today, this leads you to a wiki page th...
That covers most of the cases you’ll see in this book. There are additional ways to run Python code, though, most of which have special or narrow roles.
The next few sections take a quick look at some of these. ###### Embedding Calls In some specialized domains, Python code may be run automatically by an enclosing system.
In such cases, we say that the Python programs are embedded in (i.e., run by) another program.
The Python code itself may be entered into a text file, stored in a database, fetched from an HTML page, parsed from an XML document, and so on. But from an operational perspective, another system—not you—may tell Python to run the code you’ve created. Such an embedded execution mode is commonly used to support end-us...
Users can modify this type of system by providing or changing Python code.
Because Python code is interpreted, there is no need to recompile the entire system to incorporate the change (see Chapter 2 for more on how Python code is run). **|** ----- In this mode, the enclosing system that runs your code might be written in C, C++, or even Java when the Jython system is used.
As an example, it’s possible to create and run strings of Python code from a C program by calling functions in the Python runtime API (a set of services exported by the libraries created when Python is compiled on your machine): ``` #include <Python.h> ... Py_Initialize(); // This is C, not Pyth...
C programs may also gain access to Python modules and objects and process or execute them using other Python API tools. This book isn’t about Python/C integration, but you should be aware that, depending on how your organization plans to use Python, you may or may not be the one who actually starts the Python programs...
Regardless, you can usually still use the interactive and file-based launching techniques described here to test code in isolation from those enclosing systems that may eventually use it.[*] ###### Frozen Binary Executables Frozen binary executables, described in Chapter 2, are packages that combine your program’s by...
This approach enables Python programs to be launched in the same ways that you would launch any other executable program (icon clicks, command lines, etc.).
While this option works well for delivery of products, it is not really intended for use during program development; you normally freeze just before shipping (after development is finished).
See the prior chapter for more on this option. ###### Text Editor Launch Options As mentioned previously, although they’re not full-blown IDE GUIs, most programmer-friendly text editors have support for editing, and possibly running, Python programs.
Such support may be built in or fetchable on the Web. For instance, if you are familiar with the Emacs text editor, you can do all your Python editing and launching from inside that text editor.
See the text editor resources page at http://www.python _.org/editors for more details, or search the Web for the phrase “Python editors.”_ - See Programming Python (O’Reilly) for more details on embedding Python in C/C++.
The embedding API can call Python functions directly, load modules, and more.
Also, note that the Jython system allows Java programs to invoke Python code using a Java-based API (a Python interpreter class). **|** ----- ###### Still Other Launch Options Depending on your platform, there may be additional ways that you can start Python programs.
For instance, on some Macintosh systems you may be able to drag Python program file icons onto the Python interpreter icon to make them execute, and on Windows you can always start Python scripts with the Run...
option in the Start menu. Additionally, the Python standard library has utilities that allow Python programs to be started by other Python programs in separate processes (e.g., os.popen, os.system), and Python scripts might also be spawned in larger contexts like the Web (for instance, a web page might invoke a script ...
Indeed, many of the execution and launch details presented arose during the shelf life of this book’s various editions.
As with program execution options, it’s not impossible that new program launch options may arise over time. New operating systems, and new versions of existing systems, may also provide execution techniques beyond those outlined here.
In general, because Python keeps pace with such changes, you should be able to launch Python programs in whatever way makes sense for the machines you use, both now and in the future—be that by drawing on tablet PCs or PDAs, grabbing icons in a virtual reality, or shouting a script’s name over your coworkers’ conversat...
If I knew what the future truly held, though, I would probably be talking to a stockbroker instead of writing these words! ###### Which Option Should I Use? With all these options, one question naturally arises: which one is best for me?
In general, you should give the IDLE interface a try if you are just getting started with Python. It provides a user-friendly GUI environment and hides some of the underlying configuration details.
It also comes with a platform-neutral text editor for coding your scripts, and it’s a standard and free part of the Python system. If, on the other hand, you are an experienced programmer, you might be more comfortable with simply the text editor of your choice in one window, and another window for launching the progr...
Because the choice of development environments is very subjective, I can’t offer much more in the **|** ----- way of universal guidelines; in general, whatever environment you like to use will be the best for you to use. ###### Debugging Python Code Naturally, none of my readers or students ever have bugs in thei...
By this, I don’t mean that Python programmers don’t debug their code—but when you make a mistake in a Python program, you get a very useful and readable error message (you’ll get to see some soon, if you haven’t already). If you already know Python, and especially for your own code, this is often enough—read the error ...
For many, this _is debugging in Python. It may not always be ideal for larger system you didn’t_ write, though. - Insert `print` **statements.
Probably the main way that Python programmers debug** their code (and the way that I debug Python code) is to insert print statements and run again.
Because Python runs immediately after changes, this is usually the quickest way to get more information than error messages provide.
The `print` statements don’t have to be sophisticated—a simple “I am here” or display of variable values is usually enough to provide the context you need.
Just remember to delete or comment out (i.e., add a # before) the debugging prints before you ship your code! - Use IDE GUI debuggers.
For larger systems you didn’t write, and for beginners who want to trace code in more detail, most Python development GUIs have some sort of point-and-click debugging support.
IDLE has a debugger too, but it doesn’t appear to be used very often in practice—perhaps because it has no command line, or perhaps because adding print statements is usually quicker than setting up a GUI debugging session.
To learn more, see IDLE’s Help, or simply try it on your own; its basic interface is described in the section “Advanced IDLE Tools” on page 62.
Other IDEs, such as Eclipse, NetBeans, Komodo, and Wing IDE, offer advanced point-and-click debuggers as well; see their documentation if you use them. - Use the pdb command-line debugger.
For ultimate control, Python comes with a source-code debugger named pdb, available as a module in Python’s standard library.
In pdb, you type commands to step line by line, display variables, set and clear breakpoints, continue to a breakpoint or error, and so on.
pdb can be launched interactively by importing it, or as a top-level script. Either way, because you can type commands to control the session, it provides a powerful debugging tool.