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

(yzsuai) #1

Example 5-21. PP4E\System\Processes\pipe-thread.py


anonymous pipes and threads, not processes; this version works on Windows


import os, time, threading


def child(pipeout):
zzz = 0
while True:
time.sleep(zzz) # make parent wait
msg = ('Spam %03d' % zzz).encode() # pipes are binary bytes
os.write(pipeout, msg) # send to parent
zzz = (zzz+1) % 5 # goto 0 after 4


def parent(pipein):
while True:
line = os.read(pipein, 32) # blocks until data sent
print('Parent %d got [%s] at %s' % (os.getpid(), line, time.time()))


pipein, pipeout = os.pipe()
threading.Thread(target=child, args=(pipeout,)).start()
parent(pipein)


Since threads work on standard Windows Python, this script does too. The output is
similar here, but the speakers are in-process threads, not processes (note that because
of its simple-minded infinite loops, at least one of its threads may not die on a Ctrl-C—
on Windows you may need to use Task Manager to kill the python.exe process running
this script or close its window to exit):


C:\...\PP4E\System\Processes> pipe-thread.py
Parent 8876 got [b'Spam 000'] at 1268579215.71
Parent 8876 got [b'Spam 001'] at 1268579216.73
Parent 8876 got [b'Spam 002'] at 1268579218.74
Parent 8876 got [b'Spam 003'] at 1268579221.75
Parent 8876 got [b'Spam 004'] at 1268579225.76
Parent 8876 got [b'Spam 000'] at 1268579225.76
Parent 8876 got [b'Spam 001'] at 1268579226.77
Parent 8876 got [b'Spam 002'] at 1268579228.79
...etc.: Ctrl-C or Task Manager to exit...

Bidirectional IPC with anonymous pipes


Pipes normally let data flow in only one direction—one side is input, one is output.
What if you need your programs to talk back and forth, though? For example, one
program might send another a request for information and then wait for that informa-
tion to be sent back. A single pipe can’t generally handle such bidirectional conversa-
tions, but two pipes can. One pipe can be used to pass requests to a program and
another can be used to ship replies back to the requestor.


This really does have real-world applications. For instance, I once added a GUI interface
to a command-line debugger for a C-like programming language by connecting two
processes with pipes this way. The GUI ran as a separate process that constructed and


228 | Chapter 5: Parallel System Tools

Free download pdf