Python DevCenter
oreilly.comSafari Books Online.Conferences.

advertisement


Understanding Network I/O: From Spectator to Participant
Pages: 1, 2, 3, 4

A Simple Client with a GUI

This example uses Tkinter, one of several open source GUI libraries available for Python. Tkinter is the de facto standard Python GUI, and is typically included with the language (see Installation Notes for details). An Introduction to Tkinter is a highly accessible tutorial on using this library in your own programs.



Example 6. A simple GUI client

import urllib  # Library for retrieving files using a URL.
import re      # Library for finding patterns in text.

import sys     # Various system facilities.
import Tkinter # The Tkinter GUI library.

# The class for our simple GUI.
class SimpleGUI:

    # Class constructor -- note that the first argument, 'self'
    # is a reference to the object being created.
    def __init__(self, master, title, url, pattern, samplerate):

        # Save the URL and the regular expression pattern as part
        # of the object being constructed -- we'll need them later.
        self.__url = url  
        self.__pattern = pattern

        # The samplerate is per hour, while Tkinter uses milliseconds
        # to calculate delays.  Thus, we convert a per hour rate
        # into a delay value in milliseconds, and save it inside our
        # object for later use.
        self.__delay = int(60*60*1000.0/samplerate)

        # The master is our parent widget, we'll need to make calls
        # to it later, so save the reference inside the object.  In
        # this case, our parent widget will actually be the Tkinter
        # root widget itself.
        self.__master = master

        # Set the root window title.
        master.title(title)

        # Create a frame, to hold our controls.
        frame = Tkinter.Frame(master)

        # This makes the frame visible; see "An Introduction to Tkinter"
        # for more details.
        frame.pack()  

        # Create a button; its action ('command') is to exit the
        # program.  We pack the button in the first available position
        # in the frame, furthest to the right.  If you want to know
        # about other layout options for your windows, see
        # "An Introduction to Tkinter".
        Tkinter.Button(frame, text="EXIT",
                       command=frame.quit).pack(side=Tkinter.RIGHT)

        # A label widget will be used to display the output.  We save
        # a reference to it in our object, and again pack towards the
        # right of the frame.
        self.__show = Tkinter.Label(frame)
        self.__show.pack(side=Tkinter.RIGHT)

        # We've set everything up -- now run our sampling routine.
        self.__sample()

    # The sampling routine, which is a member function of our class.
    # It is almost the same as the simple command-line client shown
    # previously.  Note that this routine operates on an object of
    # our SimpleGUI class -- this object is passed via the 'self'
    # parameter of the routine.
    def __sample(self):
        
        # Open and read the web page.
        webpage = urllib.urlopen(self.__url).read()

        # Pattern which matches text like '66.9 F'.  The last
        # argument ('re.S') is a flag, which effectively causes
        # newlines to be treated as ordinary characters.
        match = re.search(self.__pattern,webpage,re.S)

        # Display the matched text and a descriptive message.
        self.__show.config(text='it is now '+match.group(1)+' degrees.')

        # Tell the Tkinter root to call our sample routine again
        # after the delay we have set earlier.  This will update
        # our temperature display periodically.
        self.__master.after(self.__delay, self.__sample)

# --- End of SimpleGUI Class ---

# Create the Tkinter root widget.
tkroot = Tkinter.Tk()

# Create an instance of our SimpleGUI class.
simplegui = SimpleGUI(tkroot,
    # The window title
    'In New York ...',

    # The URL of the page to retrieve.
    'http://weather.noaa.gov/weather/current/KNYC.html',

    # The regular expression pattern to apply.
    r'(-?\d+(?:\.\d+)?) F',

    # How many times to sample per hour.
    1)

# Start the Tkinter mainloop.  This will allow our application
# to respond to events, such as the 'EXIT' button, and to make
# periodic calls to the sample routine we have defined.
tkroot.mainloop()

In this GUI-based version of a simple web client, the network I/O is performed in the sampling routine. The Tkinter framework's event loop will call this routine after the specified delay, or perhaps later, if the system is heavily loaded with other events. The routine then reschedules itself. Here is a screenshot of the GUI-based simple client.

the GUI-based simple client

Figure 1. Screenshot of the GUI-based simple client

With a GUI, it is also possible to show the results in formats other than plain text. For example, temperature readings can be used to animate a picture of a thermometer.

Remember to Tread Lightly!

When accessing network resources, it is important to tread lightly. This is why the GUI client example only samples once per hour — quite sufficient for checking the weather. On a fast network connection, even a simple client like this is capable of generating multiple requests per second. If you then give the program to others, and they pass it on, soon the operator of the server you are accessing can be experiencing a lot of unnecessary extra traffic.

The Internet — and the multitude of publicly accessible servers on it — are a shared resource. By writing well-behaved programs that take only what they need, you are using this resource carefully and wisely. Thus, we preserve the free and open Internet for others as well as ourselves.

Pages: 1, 2, 3, 4

Next Pagearrow





Sponsored by: