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

(yzsuai) #1
(the non-GUI) can connect. One way or another, the GUI has to start before the
non-GUI connects to it or the non-GUI script will be denied a connection and
will fail.


  • Because of the buffered text nature of the socket.makefile objects used for streams
    here, the client program is required to flush its printed output with
    sys.stdout.flush to send data to the GUI—without this call, the GUI receives and
    displays nothing. As we’ll learn in Chapter 12, this isn’t required for command
    pipes, but it is when streams are reset to wrapped sockets as done here. These
    wrappers don’t support unbuffered modes in Python 3.X, and there is no equivalent
    to the -u flag in this context (more on -u and command pipes in the next section).


Stay tuned for much more on this example and topic in Chapter 12. Its socket client/
server model works well and is a general approach to connecting GUI and non-GUI
code, but there are other coding alternatives worth exploring in the next section before
we move on.


Adding a GUI As a Separate Program: Command Pipes


The net effect of the two programs of the preceding section is similar to a GUI program
reading the output of a shell command over a pipe file with os.popen (or the
subprocess.Popen interface upon which it is based). As we’ll see later, though, sockets
also support independent servers, and can link programs running on remote machines
across a network—a much larger idea we’ll be exploring in Chapter 12.


Perhaps subtler and more significant for our GUI exploration here is the fact that with-
out an after timer loop and nonblocking input sources of the sort used in the prior
section, the GUI may become stuck and unresponsive while waiting for data from the
non-GUI program and may not be able to handle more than one data stream.


For instance, consider the guiStreams call we wrote in Example 10-12 to redirect the
output of a shell command spawned with os.popen to a GUI window. We could use
this with simplistic code like that in Example 10-26 to capture the output of a spawned
Python program and display it in a separately running GUI program’s window. This is
as concise as it is because it relies on the read/write loop and GuiOutput class in Exam-
ple 10-12 to both manage the GUI and read the pipe; it’s essentially the same as one of
the options in that example’s self-test code, but we read the printed output of a Python
program here.


Example 10-26. PP4E\Gui\Tools\pipe-gui1.py


GUI reader side: route spawned program standard output to a GUI window


from PP4E.Gui.Tools.guiStreams import redirectedGuiShellCmd # uses GuiOutput
redirectedGuiShellCmd('python -u pipe-nongui.py') # -u: unbuffered


654 | Chapter 10: GUI Coding Techniques

Free download pdf