C:\...\PP4E\Gui\ShellGui\temp> python ..\mytools.py list
PP4E scrolledtext
list test
Packer: packed.all ['spam.txt', 'ham.txt', 'eggs.txt']
packing: spam.txt
packing: ham.txt
packing: eggs.txt
Unpacker: packed.all
creating: spam.txt
creating: ham.txt
creating: eggs.txt
This may be less than ideal for a GUI’s users; they may not expect (or even be able to
find) the command-line console. We can do better here, by redirecting stdout to an
object that throws text up in a GUI window as it is received. You’ll have to read the
next section to see how.
GuiStreams: Redirecting Streams to Widgets
On to our next GUI coding technique: in response to the challenge posed at the end of
the last section, the script in Example 10-12 arranges to map input and output sources
to pop-up windows in a GUI application, much as we did with strings in the stream
redirection topics in Chapter 3. Although this module is really just a first-cut prototype
and needs improvement itself (e.g., each input line request pops up a new input
dialog—not exactly award winning ergonomics!), it demonstrates the concepts in
general.
Example 10-12’s GuiOutput and GuiInput objects define methods that allow them to
masquerade as files in any interface that expects a real file. As we learned earlier in
Chapter 3, this includes both the print and input built-in functions for accessing
standard streams, as well as explicit calls to the read and write methods of file objects.
The two top-level interfaces in this module handle common use cases:
- The redirectedGuiFunc function uses this plug-and-play file compatibility to run a
function with its standard input and output streams mapped completely to pop-
up windows rather than to the console window (or wherever streams would oth-
erwise be mapped in the system shell). - The redirectedGuiShellCmd function similarly routes the output of a spawned shell
command line to a pop-up window. It can be used to display the output of any
program in a GUI—including that printed by a Python program.
The module’s GuiInput and GuiOutput classes can also be used or customized directly
by clients that need to match a more direct file method interface or need more fine-
grained control over the process.
GuiStreams: Redirecting Streams to Widgets | 623