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

(yzsuai) #1

Running Programs


To be more independent, Example 8-34 spawns each of the four demo launchers as
independent programs (processes), using the launchmodes module we wrote at the end
of Chapter 5. This works only because the demos were written as both importable
classes and runnable scripts. Launching them here makes all their names main when
run, because they are separate, stand-alone programs; this in turn kicks off the main
loop call at the bottom of each of their files.


Example 8-34. PP4E\Gui\Tour\demoAll-prg.py


"""
4 demo classes run as independent program processes: command lines;
if one window is quit now, the others will live on; there is no simple way to
run all report calls here (though sockets and pipes could be used for IPC), and
some launch schemes may drop child program stdout and disconnect parent/child;
"""


from tkinter import *
from PP4E.launchmodes import PortableLauncher
demoModules = ['demoDlg', 'demoRadio', 'demoCheck', 'demoScale']


for demo in demoModules: # see Parallel System Tools
PortableLauncher(demo, demo + '.py')() # start as top-level programs


root = Tk()
root.title('Processes')
Label(root, text='Multiple program demo: command lines', bg='white').pack()
root.mainloop()


Make sure the PP4E directory’s container is on your module search path (e.g.,
PYTHONPATH) to run this; it imports an example module from a different directory.
As Figure 8-35 shows, the display generated by this script is similar to the prior one;
all four demos come up in windows of their own.


This time, though, these are truly independent programs: if any one of the five windows
here is quit, the others live on. The demos even outlive their parent, if the main window
is closed. On Windows, in fact, the shell window where this script is started becomes
active again when the main window is closed, even though the spawned demos con-
tinue running. We’re reusing the demo code as program, not module.


478 | Chapter 8: A tkinter Tour, Part 1

Free download pdf