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

(yzsuai) #1

Notice how we’re displaying bytes strings in Figure 10-14—even though the non-GUI
script prints text, the GUI script reads it with the raw socket interface, and sockets deal
in binary byte strings in Python 3.X.


Run this example by yourself for a closer look. In high-level terms, the GUI script
spawns the non-GUI script and displays a pop-up window that shows the text printed
by the non-GUI script (the date and time). The non-GUI script can keep running linear,
procedural code to produce data, because only the GUI script’s process runs an event-
driven mainloop call.


Moreover, unlike our earlier stream redirection explorations which simply connected
the script’s streams to GUI objects running in the same process, this decoupled two-
process approach prevents the GUI from being blocked while waiting for the script to
produce output; the GUI process remains fully and independently active, and simply
picks up new results as they appear (more on this in the next section). This model is
similar in spirit to our earlier thread queue examples, but the actors here are separate
programs linked by a socket, not in-process function calls.


Although we aren’t going to get into enough socket details in this chapter to fully
explain this script’s code, there are a few fine points worth underscoring here:



  • This example should probably be augmented to detect and handle an end-of-file
    signal from the spawned program, and then terminate its timer loop.

  • The non-GUI script could also start the GUI instead, but in the socket world, the
    server’s end (the GUI) must be configured to accept connections before the client


Figure 10-14. Messages printed to a GUI from a non-GUI program (socket)


More Ways to Add GUIs to Non-GUI Code | 653
Free download pdf