The Input Trick
The Input Trick
Unfortunately, on Windows, the result of clicking on a file icon may not be incredibly
satisfying. 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 none yet
available. 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!
Version skew note: If you are working in Python 2.6 or earlier, use
raw_input() instead of input() in this code. 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()).
† 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.
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 avail-
able in the imp standard library module (this function is also a simple built-in in Python
2.6, but not in 3.0):
>>> from imp import reload # Must load from module in 3.0
>>> reload(script1)
win32
65536
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!
<module 'script1' from 'script1.py'>
>>>
The from statement here simply copies a name out of a module (more on this soon).
The reload function itself loads and runs the current version of your file’s code, picking
up changes if you’ve changed and saved it in another window.
This allows you to edit and pick up new code on the fly within the current Python
interactive session. 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 reload it. 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.
This may be one of the world’s simplest Python modules (it contains a single assignment
statement), but it’s enough to illustrate the point. When this file is imported, its code
is run to generate the module’s attribute. The assignment statement creates a module
attribute named title.
In general, the dot expression syntax object.attribute lets you fetch any attribute
attached to any object, and this is a very common operation in Python code. 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 directly: no need to qualify
The Meaning of Life
As you’ll see in more detail later, from is just like an import, with an extra assignment
to names in the importing component. 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 the
module file myfile.py are executed, and the importing component (here, the interactive
prompt) gains access to names assigned at the top level of the file. 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 practice, module files usually define more than one name to be used in and outside
the files. 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.