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

(yzsuai) #1

window = Tk()
Button(window, text='GO!', command=launch).pack()
window.mainloop()


The -u unbuffered flag is crucial here again—without it, you won’t see the text output
window. The GUI will be blocked in the initial pipe input call indefinitely because the
spawned program’s standard output will be queued up in an in-memory buffer.


On the other hand, this -u unbuffered flag doesn’t prevent blocking in the prior sec-
tion’s socket scheme, because that example resets streams to other objects after the
spawned program starts; more on this in Chapter 12. Also remember that the buffering
argument in os.popen (and subprocess.Popen) controls buffering in the caller, not in the
spawned program; -u pertains to the latter.


The specter of blocking input calls


Either way we code them, however, when the GUIs of Example 10-26 and Exam-
ple 10-28 are run they become unresponsive for two seconds at a time while they read
data from the os.popen pipe. In fact, they are just plain sluggish—window moves, re-
sizes, redraws, raises, and so on, are delayed for up to two seconds, until the non-GUI
program sends data to the GUI to make the pipe read call return. Perhaps worse, if you
press the “GO!” button twice in the second version of the GUI, only one window
updates itself every two seconds, because the GUI is stuck in the second button press
callback—it never exits the loop that reads from the pipe until the spawned non-GUI


Figure 10-15. Messages printed to a GUI from a non-GUI program (command pipe)


656 | Chapter 10: GUI Coding Techniques

Free download pdf