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

(yzsuai) #1

import sys
from socket import *
port = 50008
host = 'localhost'


def redirectOut(port=port, host=host):
"""
connect caller's standard output stream to a socket for GUI to listen;
start caller after listener started, else connect fails before accept
"""
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port)) # caller operates in client mode
file = sock.makefile('w') # file interface: text, bufferred
sys.stdout = file # make prints go to sock.send


def redirectIn(port=port, host=host): ... # see Chapter 12
def redirectBothAsClient(port=port, host=host): ... # see Chapter 12
def redirectBothAsServer(port=port, host=host): ... # see Chapter 12


Next, Example 10-24 uses Example 10-23 to redirect its prints to a socket on which a
GUI server program may listen; this requires just two lines of code at the top of the
script, and is done selectively based upon the value of a command-line argument (with-
out the argument, the script runs in fully non-GUI mode):


Example 10-24. PP4E\Gui\Tools\socket-nongui.py


non-GUI side: connect stream to socket and proceed normally


import time, sys
if len(sys.argv) > 1: # link to gui only if requested
from socket_stream_redirect0 import * # connect my sys.stdout to socket
redirectOut() # GUI must be started first as is


non-GUI code


while True: # print data to stdout:
print(time.asctime()) # sent to GUI process via socket
sys.stdout.flush() # must flush to send: buffered!
time.sleep(2.0) # no unbuffered mode, -u irrelevant


And finally, the GUI part of this exchange is the program in Example 10-25. This script
implements a GUI to display the text printed by the non-GUI program, but it knows
nothing of that other program’s logic. For the display, the GUI program prints to the
stream redirection object we met earlier in this chapter (Example 10-12); because this
program runs a GUI mainloop call, this all just works.


We’re also running a timer loop here to detect incoming data on the socket as it arrives,
instead of waiting for the non-GUI program to run to completion. Because the socket
is set to be nonblocking, input calls don’t wait for data to appear, and hence, do not
block the GUI.


More Ways to Add GUIs to Non-GUI Code | 651
Free download pdf