Text
stringlengths
1
9.41k
You will normally want to click (or otherwise run) the source code file, in order to pick up your most recent changes. To launch the file here, simply click on the icon for script1.py. _Figure 3-1.
On Windows, Python program files show up as icons in file explorer windows and can_ _automatically be run with a double-click of the mouse (though you might not see printed output or_ _error messages this way)._ **|** ----- ###### The input Trick Unfortunately, on Windows, the result of clicking on a file icon may...
In fact, as it is, this example script generates a perplexing “flash” when clicked—not exactly the sort of feedback that budding Python programmers usually hope for!
This is not a bug, but has to do with the way the Windows version of Python handles printed output. By default, Python generates a pop-up black DOS console window to serve as a clicked file’s input and output.
If a script just prints and exits, well, it just prints and exits— the console window appears, and text is printed there, but the console window closes and disappears on program exit.
Unless you are very fast, or your machine is very slow, you won’t get to see your output at all.
Although this is normal behavior, it’s probably not what you had in mind. Luckily, it’s easy to work around this.
If you need your script’s output to stick around when you launch it with an icon click, simply put a call to the built-in input function at the very bottom of the script (raw_input in 2.6: see the note ahead).
For example: _# A first Python script_ ``` import sys # Load a library module print(sys.platform) print(2 ** 100) # Raise 2 to a power x = 'Spam!' print(x * 8) # String repetition ``` `input()` _# <== ADDED_ In general, `input reads the next line of standard input, waiting if there is ...
The net effect in this context will be to pause the script, thereby keeping the output window shown in Figure 3-2 open until you press the Enter key. _Figure 3-2.
When you click a program’s icon on Windows, you will be able to see its printed output_ _if you include an input call at the very end of the script.
But you only need to do so in this context!_ **|** ----- Now that I’ve shown you this trick, keep in mind that it is usually only required for Windows, and then only if your script prints text and exits and only if you will launch the script by clicking its file icon.
You should add this call to the bottom of your toplevel files if and only if all of these three conditions apply.
There is no reason to add this call in any other contexts (unless you’re unreasonably fond of pressing your computer’s Enter key!).[†] That may sound obvious, but it’s another common mistake in live classes. Before we move ahead, note that the input call applied here is the input counterpart of using the print stateme...
It is the simplest way to read user input, and it is more general than this example implies.
For instance, input: - Optionally accepts a string that will be printed as a prompt (e.g., `input('Press` ``` Enter to exit')) ``` - Returns to your script a line of text read as a string (e.g., nextinput = input()) - Supports input stream redirections at the system shell level (e.g., python spam.py ``` < inp...
The former was renamed to ``` the latter in Python 3.0.
Technically, 2.6 has an input too, but it also _evaluates strings as though they are program code typed into a script,_ and so will not work in this context (an empty string is an error).
Python 3.0’s input (and 2.6’s raw_input) simply returns the entered text as a string, unevaluated.
To simulate 2.6’s input in 3.0, use eval(input()). ###### Other Icon-Click Limitations Even with the input trick, clicking file icons is not without its perils.
You also may not get to see Python error messages.
If your script generates an error, the error message text is written to the pop-up console window—which then immediately disappears! Worse, adding an input call to your file will not help this time because your script will likely abort long before it reaches this call.
In other words, you won’t be able to tell what went wrong. † It is also possible to completely suppress the pop-up DOS console window for clicked files on Windows. Files whose names end in a .pyw extension will display only windows constructed by your script, not the default DOS console window.
.pyw files are simply .py source files that have this special operational behavior on Windows.
They are mostly used for Python-coded user interfaces that build windows of their own, often in conjunction with various techniques for saving printed output and errors to files. **|** ----- Because of these limitations, it is probably best to view icon clicks as a way to launch programs after they have been debugg...
Especially when starting out, use other techniques—such as system command lines and IDLE (discussed further in the section “The IDLE User Interface” on page 58)—so that you can see generated error messages and view your normal output without resorting to coding tricks.
When we discuss exceptions later in this book, you’ll also learn that it is possible to intercept and recover from errors so that they do not terminate your programs.
Watch for the discussion of the try statement later in this book for an alternative way to keep the console window from closing on errors. ###### Module Imports and Reloads So far, I’ve been talking about “importing modules” without really explaining what this term means.
We’ll study modules and larger program architecture in depth in Part V, but because imports are also a way to launch programs, this section will introduce enough module basics to get you started. In simple terms, every file of Python source code whose name ends in a .py extension is a module.
Other files can access the items a module defines by importing that module; ``` import operations essentially load another file and grant access to that file’s contents. ``` The contents of a module are made available to the outside world through its attributes (a term I’ll define in the next section). This module-ba...
Larger programs usually take the form of multiple module files, which import tools from other module files.
One of the modules is designated as the main or top-level file, and this is the one launched to start the entire program. We’ll delve into such architectural issues in more detail later in this book.
This chapter is mostly interested in the fact that import operations run the code in a file that is being loaded as a final step.
Because of this, importing a file is yet another way to launch it. For instance, if you start an interactive session (from a system command line, from the Start menu, from IDLE, or otherwise), you can run the script1.py file you created earlier with a simple import (be sure to delete the input line you added in the pr...
After the first import, later imports do nothing, even if you change and save the module’s source file again in another window: ``` >>> import script1 >>> import script1 ``` This is by design; imports are too expensive an operation to repeat more than once per file, per program run.
As you’ll learn in Chapter 21, imports must find files, compile them to byte code, and run the code. If you really want to force Python to run the file again in the same session without stopping and restarting the session, you need to instead call the reload function available in the imp standard library module (this ...
In this session, for example, the second `print statement in` _script1.py was changed in another window to print 2 ** 16 between the time of the_ first import and the reload call. The reload function expects the name of an already loaded module object, so you have to have successfully imported a module once before you...
Notice that reload also expects parentheses around the module object name, whereas import does not. ``` reload is a function that is called, and import is a statement. ``` That’s why you must pass the module name to reload as an argument in parentheses, and that’s why you get back an extra output line when reloading.
The last output line is just the display representation of the `reload call’s return value, a Python module` object.
We’ll learn more about using functions in general in Chapter 16. **|** ----- _Version skew note: Python 3.0 moved the reload built-in function to the_ ``` imp standard library module.
It still reloads files as before, but you must ``` import it in order to use it.
In 3.0, run an `import imp and use` ``` imp.reload(M), or run a from imp import reload and use reload(M), as ``` shown here.
We’ll discuss import and from statements in the next section, and more formally later in this book. If you are working in Python 2.6 (or 2.X in general), reload is available as a built-in function, so no import is required.
In Python 2.6, reload is available in both forms—built-in and module function—to aid the transition to 3.0.
In other words, reloading is still available in 3.0, but an extra line of code is required to fetch the reload call. The move in 3.0 was likely motivated in part by some well-known issues involving reload and from statements that we’ll encounter in the next section.
In short, names loaded with a from are not directly updated by a `reload, but names accessed with an` `import statement are.
If your` names don’t seem to change after a `reload, try using` `import and` ``` module.attribute name references instead. ###### The Grander Module Story: Attributes ``` Imports and reloads provide a natural program launch option because import operations execute files as a last step.
In the broader scheme of things, though, modules serve the role of libraries of tools, as you’ll learn in Part V.
More generally, a module is mostly just a package of variable names, known as a namespace.
The names within that package are called attributes—an attribute is simply a variable name that is attached to a specific object (like a module). In typical use, importers gain access to all the names assigned at the top level of a module’s file.
These names are usually assigned to tools exported by the module— functions, classes, variables, and so on—that are intended to be used in other files and other programs.
Externally, a module file’s names can be fetched with two Python statements, import and from, as well as the reload call. To illustrate, use a text editor to create a one-line Python module file called myfile.py with the following contents: ``` title = "The Meaning of Life" ``` This may be one of the world’s simple...
When this file is imported, its code is run to generate the module’s attribute.
The assignment statement creates a module attribute named title. **|** ----- You can access this module’s title attribute in other components in two different ways. First, you can load the module as a whole with an import statement, and then qualify the module name with the attribute name to fetch it: `% python` _...
Here, we’ve used it to access the string variable title inside the module myfile—in other words, myfile.title. Alternatively, you can fetch (really, copy) names out of a module with from statements: `% python` _# Start Python_ `>>> from myfile import title` _# Run file; copy its names_ `>>> print(title)` _# Use name ...
Technically, from copies a module’s attributes, such that they become simple variables in the recipient—thus, you can simply refer to the imported string this time as title (a variable) instead of myfile.title (an attribute reference).[‡] Whether you use import or from to invoke an import operation, the statements in ...
There’s only one such name in this simple example—the variable title, assigned to a string—but the concept will be more useful when you start defining objects such as functions and classes in your modules: such objects become reusable software components that can be accessed by name from one or more client modules. In...
Here’s an example that defines three: ``` a = 'dead' # Define three attributes b = 'parrot' # Exported to other files c = 'sketch' print(a, b, c) # Also used in this file ``` This file, threenames.py, assigns three variables, and so generates three attributes for the outside world.
It also uses its own three variables in a print statement, as we see when we run this as a top-level file: ‡ Notice that import and from both list the name of the module file as simply myfile without its .py suffix.
As you’ll learn in Part V, when Python looks for the actual file, it knows to include the suffix in its search procedure.
Again, you must include the .py suffix in system shell command lines, but not in import statements. **|** ----- ``` % python threenames.py dead parrot sketch ``` All of this file’s code runs as usual the first time it is imported elsewhere (by either an ``` import or from).
Clients of this file that use import get a module with attributes, while ``` clients that use from get copies of the file’s names: ``` % python ``` `>>> import threenames` _# Grab the whole module_ ``` dead parrot sketch >>> >>> threenames.b, threenames.c ('parrot', 'sketch') >>> ``` `>>> from threenames...
The following returns a Python list of strings (we’ll start studying lists in the next chapter): ``` >>> dir(threenames) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a', 'b', 'c'] ``` I ran this on Python 3.0 and 2.6; older Pythons may return fewer names.
When the ``` dir function is called with the name of an imported module passed in parentheses like ``` this, it returns all the attributes inside that module.
Some of the names it returns are names you get “for free”: names with leading and trailing double underscores are builtin names that are always predefined by Python and that have special meaning to the interpreter.
The variables our code defined by assignment—a, b, and c—show up last in the dir result. ###### Modules and namespaces Module imports are a way to run files of code, but, as we’ll discuss later in the book, modules are also the largest program structure in Python programs. In general, Python programs are composed of...
Each module file is a self-contained package of variables—that is, ``` a namespace.
One module file cannot see the names defined in another file unless it explicitly imports that other file, so modules serve to minimize name collisions in your code—because each file is a self-contained namespace, the names in one file cannot clash with those in another, even if they are spelled the same way. **|** ...
We’ll discuss modules and other namespace constructs (including classes and function scopes) further later in the book.
For now, modules will come in handy as a way to run your code many times without having to retype it. _import versus from: I should point out that the from statement in a sense_ defeats the namespace partitioning purpose of modules—because the ``` from copies variables from one file to another, it can cause sam...
This essentially collapses namespaces together, at least in terms of the copied variables. Because of this, some recommend using import instead of from.
I won’t go that far, though; not only does from involve less typing, but its purported problem is rarely an issue in practice.
Besides, this is something _you control by listing the variables you want in the from; as long as you_ understand that they’ll be assigned values, this is no more dangerous than coding assignment statements—another feature you’ll probably want to use! ###### import and reload Usage Notes For some reason, once people ...
This approach can quickly lead to confusion, though—you need to remember when you’ve imported to know if you can reload, you need to remember to use parentheses when you call `reload (only), and you need to remember to use` ``` reload in the first place to get the current version of your code to run.
Moreover, reloads ``` aren’t transitive—reloading a module reloads that module only, not any modules it may import—so you sometimes have to reload multiple files. Because of these complications (and others we’ll explore later, including the reload/ ``` from issue mentioned in a prior note in this chapter), it’s gener...
The IDLE Run→Run Module menu option described in the next section, for example, provides a simpler and less error-prone way to run your files, and always runs the current version of your code. System shell command lines offer similar benefits.
You don’t need to use reload if you use these techniques. In addition, you may run into trouble if you use modules in unusual ways at this point in the book.
For instance, if you want to import a module file that is stored in a directory other than the one you’re working in, you’ll have to skip ahead to Chapter 21 and learn about the module search path. **|** ----- For now, if you must import, try to keep all your files in the directory you are working in to avoid compl...
As usual, though, if you find yourself running into a wall, stop running into a wall! ###### Using exec to Run Module Files In fact, there are more ways to run code stored in module files than have yet been exposed here.
For instance, the exec(open('module.py').read()) built-in function call is another way to launch files from the interactive prompt without having to import and later reload.
Each exec runs the current version of the file, without requiring later reloads (script1.py is as we left it after a reload in the prior section): ``` C:\misc> c:\python30\python >>> exec(open('script1.py').read()) win32 65536 Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam! ...change script1.py in a text edit wind...
Because of that, exec does not require module reloads after file changes—it skips the normal module import logic. On the downside, because it works as if pasting code into the place where it is called, ``` exec, like the from statement mentioned earlier, has the potential to silently overwrite ``` variables you may c...
For example, our script1.py assigns to a variable named x.
If that name is also being used in the place where exec is called, the name’s value is replaced: ``` >>> x = 999 ``` `>>> exec(open('script1.py').read())` _# Code run in this namespace by default_ ``` ...same outout... ``` `>>> x` _# Its assignments can overwrite names here_ ``` 'Spam!' ``` § If you’re burning...
If you want to import from a directory ``` other than the one you are working in, that directory must generally be listed in your PYTHONPATH setting.
For more details, see Chapter 21. **|** ----- By contrast, the basic import statement runs the file only once per process, and it makes the file a separate module namespace so that its assignments will not change variables in your scope.
The price you pay for the namespace partitioning of modules is the need to reload after changes. _Version skew note: Python 2.6 also includes an execfile('module.py')_ built-in function, in addition to allowing the form ``` exec(open('module.py')), which both automatically read the file’s ``` content.
Both of these are equivalent to the ``` exec(open('module.py').read()) form, which is more complex but ``` runs in both 2.6 and 3.0. Unfortunately, neither of these two simpler 2.6 forms is available in 3.0, which means you must understand both files and their read methods to fully understand this technique to...
In fact, the `exec form in 3.0` involves so much typing that the best advice may simply be not to do it—it’s usually best to launch files by typing system shell command lines or by using the IDLE menu options described in the next section.
For more on the 3.0 exec form, see Chapter 9. ###### The IDLE User Interface So far, we’ve seen how to run Python code with the interactive prompt, system command lines, icon clicks, and module imports and exec calls.
If you’re looking for something a bit more visual, IDLE provides a graphical user interface for doing Python development, and it’s a standard and free part of the Python system.
It is usually referred to as an integrated development environment (IDE), because it binds together various development tasks into a single view.[‖] In short, IDLE is a GUI that lets you edit, run, browse, and debug Python programs, all from a single interface.
Moreover, because IDLE is a Python program that uses the _tkinter GUI toolkit (known as Tkinter in 2.6), it runs portably on most Python plat-_ forms, including Microsoft Windows, X Windows (for Linux, Unix, and Unix-like platforms), and the Mac OS (both Classic and OS X).
For many, IDLE represents an easy-to-use alternative to typing command lines, and a less problem-prone alternative to clicking on icons. ###### IDLE Basics Let’s jump right into an example.
IDLE is easy to start under Windows—it has an entry in the Start button menu for Python (see Figure 2-1, shown previously), and it can also be selected by right-clicking on a Python program icon.
On some Unix-like systems, ‖ IDLE is officially a corruption of IDE, but it’s really named in honor of Monty Python member Eric Idle. **|** ----- you may need to launch IDLE’s top-level script from a command line, or by clicking on the icon for the idle.pyw or idle.py file located in the idlelib subdirectory of Py...
On Windows, IDLE is a Python script that currently lives in_ _C:\Py-_ _thon30\Lib\idlelib (or C:Python26\Lib\idlelib in Python 2.6).[#]_ Figure 3-3 shows the scene after starting IDLE on Windows.
The Python shell window that opens initially is the main window, which runs an interactive session (notice the ``` >>> prompt).
This works like all interactive sessions—code you type here is run im ``` mediately after you type it—and serves as a testing tool. _Figure 3-3.
The main Python shell window of the IDLE development GUI, shown here running on_ _Windows.