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

(yzsuai) #1
Wed Apr 07 09:32:32 2010
spam
Wed Apr 07 09:32:34 2010
spam
Wed Apr 07 09:32:36 2010
spam

The net effect is that -u still works around the steam buffering issue for connected
programs in 3.X, as long as you don’t reset the streams to other objects in the spawned
program as we did for socket redirection in Example 12-11. For socket redirections,
manual flush calls or replacement socket wrappers may be required.


Sockets versus command pipes


So why use sockets in this redirection role at all? In short, for server independence and
networked use cases. Notice how for command pipes it’s not clear who should be called
“server” and “client,” since neither script runs perpetually. In fact, this is one of the
major downsides of using command pipes like this instead of sockets—because the
programs require a direct spawning relationship, command pipes do not support longer-
lived or remotely running servers the way that sockets do.


With sockets, we can start client and server independently, and the server may continue
running perpetually to serve multiple clients (albeit with some changes to our utility
module’s listener initialization code). Moreover, passing in remote machine names to
our socket redirection tools would allow a client to connect to a server running on a
completely different machine. As we learned in Chapter 5, named pipes (fifos) accessed
with the open call support stronger independence of client and server, too, but unlike
sockets, they are usually limited to the local machine, and are not supported on all
platforms.


Experiment with this code on your own for more insight. Also try changing Exam-
ple 12-11 to run the client function in a spawned process instead of or in addition to
the server, with and without flush calls and time.sleep calls to defer exits; the spawning
structure might have some impact on the soundness of a given socket dialog structure
as well, which we’ll finesse here in the interest of space.


Despite the care that must be taken with text encodings and stream buffering, the utility
provided by Example 12-10 is still arguably impressive—prints and input calls are
routed over network or local-machine socket connections in a largely automatic fash-
ion, and with minimal changes to the nonsocket code that uses the module. In many
cases, the technique can extend a script’s applicability.


In the next section, we’ll use the makefile method again to wrap the socket in a file-
like object, so that it can be read by lines using normal text-file method calls and tech-
niques. This isn’t strictly required in the example—we could read lines as byte strings
with the socket recv call, too. In general, though, the makefile method comes in handy
any time you wish to treat sockets as though they were simple files. To see this at work,
let’s move on.


Making Sockets Look Like Files and Streams | 839
Free download pdf