[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Although it is more complex and requires thread support, Example 10-29’s lack of
blocking makes this redirectedGuiShellCmd much more generally useful than the orig-
inal pipe version we coded. Compared to the sockets of the prior section, though, this
solution is a bit of a mixed bag:



  • Because this GUI reads the spawned program’s standard output, no changes are
    required in the non-GUI program. Unlike the socket-based example in the prior
    section, the non-GUI program here needs no knowledge of the GUI that will display
    its results—it need not connect to a socket and need not flush its input stream, as
    required for the earlier socket-based option.

  • Although it requires no changes to the programs whose output is displayed, the
    GUI code’s complexity begins to approach that of the socket-based alternative,
    especially if you strip away the boilerplate code required for all socket programs.

  • It does not directly support running the GUI and non-GUI programs separately,
    or on remote machines. As we’ll see in Chapter 12, sockets allow data to be passed
    between programs running on the same machine or across networks.

  • Sockets apply to more use cases than displaying a program’s output stream. If the
    GUI must do more than display another program’s output, sockets become a more
    general solution—as we’ll also learn later, because sockets are bidirectional data
    streams, they allow data to be passed back and forth between two programs in
    more arbitrary ways.


Other uses for threaded pipe GUIs


Despite its tradeoffs, the thread/queue/pipe-based approach for GUIs has fairly wide
applicability. To illustrate, here’s another quick usage example. The following runs a
simple script normally from a shell/terminal window; it prints one successively longer
output line every two seconds:


C:\...\PP4E\Gui\Tools> type spams.py
import time
for i in range(1, 10, 2):
time.sleep(2) # print to standard output
print('spam' * i) # nothing GUI about this, eh?

C:\...\PP4E\Gui\Tools> python spams.py
spam
spamspamspam
spamspamspamspamspam
spamspamspamspamspamspamspam
spamspamspamspamspamspamspamspamspam

Let’s wrap this up in a GUI, with code typed at the interactive prompt for variety. The
following imports the new GUI redirection function as a library component and uses
it to create a window that displays the script’s five lines, appearing every two seconds
just as in the terminal window, followed by a final line containing reflecting the
spawned program’s exit. The resulting output window is captured in Figure 10-16:


660 | Chapter 10: GUI Coding Techniques

Free download pdf