0% found this document useful (0 votes)
17 views6 pages

The Input Trick

Uploaded by

Set-India
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views6 pages

The Input Trick

Uploaded by

Set-India
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

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!

Clicking File Icons | 49


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 top-
level 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 com-
puter’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 statement for outputs. 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
< input.txt), just as the print statement does for output
We’ll use input in more advanced ways later in this text; for instance, Chapter 10 will
apply it in an interactive loop.

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()).

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.

50 | Chapter 3: How You Run Programs


Because of these limitations, it is probably best to view icon clicks as a way to launch
programs after they have been debugged or have been instrumented to write their out-
put to a file. Especially when starting out, use other techniques—such as system
command lines and IDLE (discussed further in the section “The IDLE User Inter-
face” 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-based services model turns out to be the core idea behind program ar-
chitecture in Python. 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 prior section
first, or you’ll need to press Enter for no reason):
C:\misc> c:\python30\python
>>> import script1
win32
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

Module Imports and Reloads | 51


This works, but only once per session (really, process) by default. 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 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.

52 | Chapter 3: How You Run Programs


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 sec-
tion, 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 tran-
sition 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 opera-
tions 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 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.

Module Imports and Reloads | 53


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 # Start Python
>>> import myfile # Run file; load module as a whole
>>> print(myfile.title) # Use its attribute names: '.' to qualify
The Meaning of Life

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.

54 | Chapter 3: How You Run Programs

You might also like