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

(yzsuai) #1

test by number on command-line


###############################################################################


if name == 'main':
server = eval('server' + sys.argv[1])
client = eval('client' + sys.argv[1]) # client in this process
multiprocessing.Process(target=server).start() # server in new process
client() # reset streams in client
#import time; time.sleep(5) # test effect of exit flush


Run the test script with a client and server number on the command line to test the
module’s tools; messages display process ID numbers, and those within square brackets
reflect a transfer across streams connected to sockets (twice, when nested):


C:\...\PP4E\Internet\Sockets> test-socket_stream_redirect.py 1
server 3844 got [client 1112: 0]
server 3844 got [client 1112: 1]
server 3844 got [client 1112: 2]

C:\...\PP4E\Internet\Sockets> test-socket_stream_redirect.py 2
client 5188 got [server 2020: 0]
client 5188 got [server 2020: 1]
client 5188 got [server 2020: 2]

C:\...\PP4E\Internet\Sockets> test-socket_stream_redirect.py 3
client 7796 got [server 2780 got [client 7796: 0]]
client 7796 got [server 2780 got [client 7796: 1]]
client 7796 got [server 2780 got [client 7796: 2]]

C:\...\PP4E\Internet\Sockets> test-socket_stream_redirect.py 4
server 4288 got [client 3852 got [server 4288: 0]]
server 4288 got [client 3852 got [server 4288: 1]]
server 4288 got [client 3852 got [server 4288: 2]]

C:\...\PP4E\Internet\Sockets> test-socket_stream_redirect.py 5
server 6040 got [client 7728 got [server 6040: 0]]
server 6040 got [client 7728 got [server 6040: 1]]
server 6040 got [client 7728 got [server 6040: 2]]

If you correlate this script’s output with its code to see how messages are passed be-
tween client and server, you’ll find that print and input calls in client functions are
ultimately routed over sockets to another process. To the client functions, the socket
linkage is largely invisible.


Text-mode files and buffered output streams


Before we move on, there are two remarkably subtle aspects of the example’s code
worth highlighting:


Binary to text translations
Raw sockets transfer binary byte strings, but by opening the wrapper files in text
mode, their content is automatically translated to text strings on input and output.
Text-mode file wrappers are required if accessed through standard stream tools


832 | Chapter 12: Network Scripting

Free download pdf