id
int64
0
25.6k
text
stringlengths
0
4.59k
5,300
omitted ( the file pull down menu and quit button are goneon the other handyou get all of the rest of pyedit' functionalityincluding cut and pastesearch and replacegrep to search external filescolors and fontsundo and redoand so on even the clone option works here to open new edit windowalbeit making frame-based menu without quit or file pull downand which doesn' test for changes on exit- usage mode that could be tightened up with new pyedit top-level component class if desired for varietyif you pass third command-line argument to pyview after the image directory nameit uses it as an index into list of pyedit top-level mode classes an argument of uses the main window modewhich places the note editor below the image and window menu at top (its frame is packed into the window' remaining spacenot the slide show frame) pops up the note editor as separateindependent toplevel window (disabled when notes are turned off) and run pyedit as an embedded component nested in the slide show framewith frame menus ( includes all menu options which may or may not be appropriate in this roleand is the default limited options modefigure - captures option pyedit' main window modethere are really two independent frames on the window here-- slideshow on top and text editor on bottom the disadvantage of this over nested component or pop-up window modes is that complete gui programs
5,301
pyedit really does assume control of the program' window (including its title and window manager close button)and packing the note editor at the bottom means it might not appear for tall images run this on your own to sample the other pyedit flavorswith command line of this formc:\pp \gui\slideshowslideshowplus py /gifs the note file viewer appears only if you press the note buttonand it is erased if you press it again--pyview uses the widget pack and pack_forget methods introduced near the end of to show and hide the note viewer frame the window automatically expands to accommodate the note viewer when it is packed and displayed note that it' important that the note editor be repacked with expand=yes and fill=both when it' unhiddenor else it won' expand in some modespyedit' frame packs itself this way in guimaker when first madebut pack_forget appears towell forget it is also possible to open the note file in pyedit pop-up windowbut pyview embeds the editor by default to retain direct visual association and avoid issues if the pop up pyviewan image and notes slideshow
5,302
wrapeditor in order to catch independent destroys of the pyedit frame when it is run in either pop-up window or full-option component modes--the note editor can no longer be accessed or repacked once it' destroyed this isn' an issue in main window mode (quit ends the programor the default minimal component mode (the editor has no quitwatch for pyedit to show up embedded as component like this within another gui when we meet pymailgui in caveat hereout of the boxpyview supports as many photo formats as tkinter' photoimage object doesthat' why it looks for gif files by default you can improve this by installing the pil extension to view jpegs (and many othersbut because pil is an optional extension todayit' not incorporated into this pyview release see the end of for more on pil and image formats pyview source code because the pyview program was implemented in stagesyou need to study the union of two files and classes to understand how it truly works one file implements class that provides core slideshow functionalitythe other implements class that extends the original classto add additional features on top of the core behavior let' start with the extension classexample - adds set of features to an imported slideshow base class--note editinga delay scale and file labeland so on this is the file that is actually run to start pyview example - pp \gui\slideshow\slideshowplus py ""############################################################################pyview an image slide show with associated text notes slideshow subclass which adds note files with an attached pyedit objecta scale for setting the slideshow delay intervaland label that gives the name of the image file currently being displayedversion is python portbut also improves repacking note for expansion when it' unhiddencatches note destroys in subclass to avoid exceptions when popup window or full component editor has been closedand runs update(before inserting text into newly packed note so it is positioned correctly at line (see the book' coverage of pyedit updates############################################################################""import os from tkinter import from pp gui texteditor texteditor import from slideshow import slideshow #from slideshow_threads import slideshow size ( start shorter here(hwclass slideshowplus(slideshow) complete gui programs
5,303
self msecs msecs self editclass editclass slideshow __init__(selfparentpicdirmsecssizedef makewidgets(self)self name label(selftext='none'bg='red'relief=ridgeself name pack(fill=xslideshow makewidgets(selfbutton(selftext='note'command=self onnotepack(fill=xbutton(selftext='help'command=self onhelppack(fill=xs scale(label='speedmsec delay'command=self onscalefrom_= to= resolution= showvalue=yeslength= tickinterval= orient='horizontal' pack(side=bottomfill=xs set(self msecs need to know if editor destroyedin popup or full component modes self editorgone false class wrapeditor(self editclass)extend pyedit class to catch quit def onquit(editor)editor is pyedit instance arg subject self editorgone true self is slide show in enclosing scope self editorup false self editclass onquit(editoravoid recursion attach editor frame to window or slideshow frame if issubclass(wrapeditortexteditormain)make editor now self editor wrapeditor(self masterneed root for menu elseself editor wrapeditor(selfembedded or pop-up self editor pack_forget(hide editor initially self editorup self image none def onstart(self)slideshow onstart(selfself config(cursor='watch'def onstop(self)slideshow onstop(selfself config(cursor='hand 'def onopen(self)slideshow onopen(selfif self imageself name config(text=os path split(self image[ ])[ ]self config(cursor='crosshair'self switchnote(def quit(self)self savenote(slideshow quit(selfdef drawnext(self)slideshow drawnext(selfif self imagepyviewan image and notes slideshow
5,304
self loadnote(def onscale(selfvalue)self msecs int(valuedef onnote(self)if self editorgone has been destroyed return don' rebuildassume unwanted if self editorup#self savenote(if editor already open self editor pack_forget(save text?hide editor self editorup false else repack for expansion againelse won' expand now update between pack and insertelse line initially self editor pack(side=topexpand=yesfill=bothself editorup true else unhide/pack editor self update(see pyeditsame as loadfirst issue self loadnote(and load image note text def switchnote(self)if self editorupself savenote(self loadnote(save current image' note load note for new image def savenote(self)if self editorupcurrfile self editor getfilename(or self editor onsave(currtext self editor getalltext(but text may be empty if currfile and currtexttryopen(currfile' 'write(currtextexceptpass failure may be normal if run off cd def loadnote(self)if self image and self editoruprootext os path splitext(self image[ ]notefile root noteself editor setfilename(notefiletryself editor setalltext(open(notefileread()exceptself editor clearalltext(might not have note def onhelp(self)showinfo('about pyview''pyview version \nmay \ ( july )\ 'an image slide show\nprogramming python 'if __name__ ='__main__'import sys picdir /gifsif len(sys argv> complete gui programs
5,305
editstyle texteditorcomponentminimal if len(sys argv= tryeditstyle [texteditormaintexteditormainpopuptexteditorcomponenttexteditorcomponentminimal][int(sys argv[ ])exceptpass root tk(root title('pyview plus text notes'label(roottext="slide show subclass"pack(slideshowplus(parent=rootpicdir=picdireditclass=editstyleroot mainloop(the core functionality extended by slideshowplus lives in example - this was the initial slideshow implementationit opens imagesdisplays photosand cycles through slideshow you can run it by itselfbut you won' get advanced features such as notes and sliders added by the slideshowplus subclass example - pp \gui\slideshow\slideshow py ""#####################################################################slideshowa simple photo image slideshow in python/tkinterthe base feature set coded here can be extended in subclasses#####################################################################""from tkinter import from glob import glob from tkinter messagebox import askyesno from tkinter filedialog import askopenfilename import random size ( canvas heightwidth at startup and slideshow start imagetypes [('gif files'gif')('ppm files'ppm')('pgm files'pgm')('all files''*')for file open dialog plus jpg with tk patchplus bitmaps with bitmapimage class slideshow(frame)def __init__(selfparent=nonepicdir='msecs= size=size**args)frame __init__(selfparent**argsself size size self makewidgets(self pack(expand=yesfill=bothself opens picdir files [for labelext in imagetypes[:- ]files files glob('% /*% (picdirext)self images [(xphotoimage(file= )for in filesself msecs msecs pyviewan image and notes slideshow
5,306
self drawn true none def makewidgets(self)heightwidth self size self canvas canvas(selfbg='white'height=heightwidth=widthself canvas pack(side=leftfill=bothexpand=yesself onoff button(selftext='start'command=self onstartself onoff pack(fill=xbutton(selftext='open'command=self onopenpack(fill=xbutton(selftext='beep'command=self onbeeppack(fill=xbutton(selftext='quit'command=self onquitpack(fill=xdef onstart(self)self loop true self onoff config(text='stop'command=self onstopself canvas config(height=self size[ ]width=self size[ ]self ontimer(def onstop(self)self loop false self onoff config(text='start'command=self onstartdef onopen(self)self onstop(name askopenfilename(initialdir=self opensfiletypes=imagetypesif nameif self drawnself canvas delete(self drawnimg photoimage(file=nameself canvas config(height=img height()width=img width()self drawn self canvas create_image( image=imganchor=nwself image nameimg def onquit(self)self onstop(self update(if askyesno('pyview''really quit now?')self quit(def onbeep(self)self beep not self beep toggleor use def ontimer(self)if self loopself drawnext(self after(self msecsself ontimerdef drawnext(self)if self drawnself canvas delete(self drawnnameimg random choice(self imagesself drawn self canvas create_image( image=imganchor=nwself image nameimg if self beepself bell(self canvas update( complete gui programs
5,307
import sys if len(sys argv= picdir sys argv[ elsepicdir /gifsroot tk(root title('pyview 'root iconname('pyview'label(roottext="python slide show viewer"pack(slideshow(rootpicdir=picdirbd= relief=sunkenroot mainloop(to give you better idea of what this core base class implementsfigure - shows what it looks like if run by itself--actuallytwo copies run by themselves by script called slideshow_frameswhich is in this book' examples distributionand whose main code looks like thisroot tk(label(roottext="two embedded slide showsframes"pack(slideshow(parent=rootpicdir=picdirbd= relief=sunkenpack(side=leftslideshow(parent=rootpicdir=picdirbd= relief=sunkenpack(side=rightroot mainloop(figure - two attached slideshow objects the simple slideshow_frames scripts attach two instances of slideshow to single window-- feat possible only because state information is recorded in class instance variablesnot in globals the slideshow_toplevels script (also in the book' examples distributionattaches two slideshows to two top-level pop-up windows instead in both pyviewan image and notes slideshow
5,308
same single event loop in single process pydrawpainting and moving graphics introduced simple tkinter animation techniques (see the tour' canvasdraw variantsthe pydraw program listed here builds upon those ideas to implement more feature-rich painting program in python it adds new trails and scribble drawing modesobject and background color fillsembedded photosand more in additionit implements object movement and animation techniques--drawn objects may be moved around the canvas by clicking and draggingand any drawn object can be gradually moved across the screen to target location clicked with the mouse running pydraw pydraw is essentially tkinter canvas with keyboard and mouse event bindings to allow users to perform common drawing operations this isn' professional-grade paint programbut it' fun to play with in factyou really should--it is impossible to capture things such as object motion in this book start pydraw from the launcher bars (or run the file movingpics py from example - directlypress the key to view help message giving available commands (or read the help string in the code listingsfigure - shows pydraw after few objects have been drawn on the canvas to move any object shown hereeither click it with the middle mouse button and drag to move it with the mouse cursoror middle-click the objectand then right-click in the spot you want it to move toward in the latter casepydraw performs an animated (gradualmovement of the object to the target spot try this on the picture shown near the top of the figure--it will slowly move across your display press "pto insert photosand use left-button drags to draw shapes (note to windows usersmiddle-click is often either both mouse buttons at once or scroll wheelbut you may need to configure this in your control panel in addition to mouse eventsthere are key-press commands for tailoring sketches that won' cover here it takes while to get the hang of what all the keyboard and mouse commands dobut once you've mastered the bindingsyou too can begin generating senseless electronic artwork such as that in figure - pydraw source code like pyeditpydraw lives in single file two extensions that customize motion implementations are listed following the main module shown in example - complete gui programs
5,309
example - pp \gui\movingpics\movingpics py ""#############################################################################pydraw simple canvas paint program and object mover/animator uses time sleep loops to implement object move loopssuch that only one move can be in progress at oncethis is smooth and fastbut see the widget after and thread-based subclasses here for other techniques version has been updated to run under python ( not supported#############################################################################""helpstr """--pydraw version -mouse commandsleft set target spot left+move draw new object double left clear all objects right move current object middle select closest object middle+move drag current object pydrawpainting and moving graphics
5,310
keyboard commandsw=pick border width =pick move unit =draw ovals =draw lines =delete object =lower object =fill background =save postscript ?=help "" =pick color =pick move delay =draw rectangles =draw arcs =raise object =fill object =add photo =pick pen modes other=clear text import timesys from tkinter import from tkinter filedialog import from tkinter messagebox import picdir /gifsif sys platform[: ='win'helpfont ('courier' 'normal'elsehelpfont ('courier' 'normal'pickdelays [ pickunits [ pickwidths [ pickfills [none,'white','blue','red','black','yellow','green','purple' complete gui programs
5,311
['elastic''scribble''trails'class movingpicsdef __init__(selfparent=none)canvas canvas(parentwidth= height= bg'white'canvas pack(expand=yesfill=bothcanvas bind(''self onstartcanvas bind(''self ongrowcanvas bind(''self onclearcanvas bind(''self onmovecanvas bind(''self onselectcanvas bind(''self ondragparent bind(''self onoptionsself createmethod canvas create_oval self canvas canvas self moving [self images [self object none self where none self scribblemode parent title('pydraw moving pictures 'parent protocol('wm_delete_window'self onquitself realquit parent quit self textinfo self canvas create_text anchor=nwfont=helpfonttext='press for help'def onstart(selfevent)self where event self object none def ongrow(selfevent)canvas event widget if self object and pickpens[ ='elastic'canvas delete(self objectself object self createmethod(canvasself where xself where ystart event xevent ystop fill=pickfills[ ]width=pickwidths[ ]if pickpens[ ='scribble'self where event from here next time def onclear(selfevent)if self movingreturn ok if moving but confusing event widget delete('all'use all tag self images [self textinfo self canvas create_text anchor=nwfont=helpfonttext='press for help'def plotmoves(selfevent)diffx event self where diffy event self where plan animated moves horizontal then vertical pydrawpainting and moving graphics
5,312
repty abs(diffy/pickunits[ incrx pickunits[ ((diffx or - incry pickunits[ ((diffy or - return incrxreptxincryrepty incr per movenumber moves from last to event click /trunc div required def onmove(selfevent)traceevent('onmove'event move current object to click object self object ignore some ops during mv if object and object not in self movingmsecs int(pickdelays[ parms 'delay=% msecunits=% (msecspickunits[ ]self settextinfo(parmsself moving append(objectcanvas event widget incrxreptxincryrepty self plotmoves(eventfor in range(reptx)canvas move(objectincrx canvas update(time sleep(pickdelays[ ]for in range(repty)canvas move(object incrycanvas update(update runs other ops time sleep(pickdelays[ ]sleep until next move self moving remove(objectif self object =objectself where event def onselect(selfevent)self where event self object self canvas find_closest(event xevent )[ def ondrag(selfevent)diffx event self where diffy event self where self canvas move(self objectdiffxdiffyself where event tuple ok if object in moving throws it off course def onoptions(selfevent)keymap ' 'lambda selfself changeoption(pickwidths'pen width')' 'lambda selfself changeoption(pickfills'color')' 'lambda selfself changeoption(pickunits'move unit')' 'lambda selfself changeoption(pickdelays'move delay')' 'lambda selfself changeoption(pickpens'pen mode')' 'lambda selfself changedraw(canvas create_oval'oval')' 'lambda selfself changedraw(canvas create_rectangle'rect')' 'lambda selfself changedraw(canvas create_line'line')' 'lambda selfself changedraw(canvas create_arc'arc')' 'movingpics deleteobject' 'movingpics raiseobject' 'movingpics lowerobjectif only call pattern ' 'movingpics fillobjectuse unbound method objects ' 'movingpics fillbackgroundelse lambda passed self ' 'movingpics addphotoitem' 'movingpics savepostscript complete gui programs
5,313
trykeymap[event char](selfexcept keyerrorself settextinfo('press for help'def changedraw(selfmethodname)self createmethod method unbound canvas method self settextinfo('draw object=namedef changeoption(selflistname)list append(list[ ]del list[ self settextinfo('% =% (namelist[ ])def deleteobject(self)if self object !self textinfoself canvas delete(self objectself object none def raiseobject(self)if self objectself canvas tkraise(self objectok if object in moving erases but move goes on ok if moving raises while moving def lowerobject(self)if self objectself canvas lower(self objectdef fillobject(self)if self objecttype self canvas type(self objectif type ='image'pass elif type ='text'self canvas itemconfig(self objectfill=pickfills[ ]elseself canvas itemconfig(self objectfill=pickfills[ ]width=pickwidths[ ]def fillbackground(self)self canvas config(bg=pickfills[ ]def addphotoitem(self)if not self wherereturn filetypes=[('gif files'gif')('all files''*')file askopenfilename(initialdir=picdirfiletypes=filetypesif fileimage photoimage(file=fileload image self images append(imagekeep reference self object self canvas create_imageadd to canvas self where xself where yat last spot image=imageanchor=nwdef savepostscript(self)file asksaveasfilename(pydrawpainting and moving graphics
5,314
self canvas postscript(file=filesave canvas to file def help(self)self settextinfo(helpstr#showinfo('pydraw'helpstrdef settextinfo(selftext)self canvas dchars(self textinfo endself canvas insert(self textinfo textself canvas tkraise(self textinfodef onquit(self)if self movingself settextinfo("can' quit while move in progress"elseself realquit(std wm deleteerr msg if move in progress def traceevent(labeleventfulltrace=true)print(labelif fulltracefor atrr in dir(event)if attr[: !'__'print(attr'=>'getattr(eventattr)if __name__ ='__main__'from sys import argv if len(argv= picdir argv[ root tk(movingpics(rootroot mainloop(when this file is executed fails if run elsewhere makerun movingpics object as isonly one object can be in motion at time--requesting an object move while one is already in motion pauses the original till the new move is finished just as in ' canvasdraw examplesthoughwe can add support for moving more than one object at the same time with either after scheduled callback events or threads example - shows movingpics subclass that codes the necessary customizations to do parallel moves with after events it allows any number of objects in the canvasincluding picturesto be moving independently at once run this file directly to see the differencei could try to capture the notion of multiple objects in motion with screenshotbut would almost certainly fail example - pp \gui\movingpics\movingpics_after py ""pydraw-aftersimple canvas paint program and object mover/animator use widget after scheduled events to implement object move loopssuch that more than one can be in motion at once without having to use threadsthis does moves in parallelbut seems to be slower than time sleep versionsee also canvasdraw in tourbuilds and passes the incx/incy list at onceherewould be allmoves ([(incrx )reptx([( incry)repty"" complete gui programs
5,315
class movingpicsafter(movingpics)def domoves(selfdelayobjectidincrxreptxincryrepty)if reptxself canvas move(objectidincrx reptx - elseself canvas move(objectid incryrepty - if not (reptx or repty)self moving remove(objectidelseself canvas after(delayself domovesdelayobjectidincrxreptxincryreptydef onmove(selfevent)traceevent('onmove'event object self object move cur obj to click spot if objectmsecs int(pickdelays[ parms 'delay=% msecunits=% (msecspickunits[ ]self settextinfo(parmsself moving append(objectincrxreptxincryrepty self plotmoves(eventself domoves(msecsobjectincrxreptxincryreptyself where event if __name__ ='__main__'from sys import argv if len(argv= import movingpics movingpics picdir argv[ root tk(movingpicsafter(rootroot mainloop(when this file is executed not this module' global and fromdoesn' link names to appreciate its operationopen this script' window full screen and create some objects in its canvas by pressing "pafter an initial click to insert picturesdragging out shapesand so on nowwhile one or more moves are in progressyou can start another by middle-clicking on another object and right-clicking on the spot to which you want it to move it starts its journey immediatelyeven if other objects are in motion each object' scheduled after events are added to the same event loop queue and dispatched by tkinter as soon as possible after timer expiration if you run this subclass module directlyyou might notice that movement isn' quite as fast or as smooth as in the original (depending on your machineand the many layers of software under python)but multiple moves can overlap in time example - shows how to achieve such parallelism with threads this process worksbut as we learned in and updating guis in spawned threads is generally dangerous affair on one of my machinesthe movement that this script implements with threads was bit jerkier than the original version--perhaps pydrawpainting and moving graphics
5,316
multiple threads--but againthis can vary example - pp \gui\movingpics\movingpics_threads py ""pydraw-threadsuse threads to move objectsworks okay on windows provided that canvas update(not called by threads (else exits with fatal errorssome objs start moving immediately after drawnetc )at least some canvas method calls must be thread safe in tkinterthis is less smooth than time sleepand is dangerous in generalthreads are best coded to update global varsnot change gui""import _thread as threadtimesysrandom from tkinter import tkmainloop from movingpics import movingpicspickunitspickdelays class movingpicsthreaded(movingpics)def __init__(selfparent=none)movingpics __init__(selfparentself mutex thread allocate_lock(import sys #sys setcheckinterval( switch after each vm opdoesn' help def onmove(selfevent)object self object if object and object not in self movingmsecs int(pickdelays[ parms 'delay=% msecunits=% (msecspickunits[ ]self settextinfo(parms#self mutex acquire(self moving append(object#self mutex release(thread start_new_thread(self domove(objectevent)def domove(selfobjectevent)canvas event widget incrxreptxincryrepty self plotmoves(eventfor in range(reptx)canvas move(objectincrx canvas update(time sleep(pickdelays[ ]this can change for in range(repty)canvas move(object incrycanvas update(update runs other ops time sleep(pickdelays[ ]sleep until next move #self mutex acquire(self moving remove(objectif self object =objectself where event #self mutex release(if __name__ ='__main__'root tk( complete gui programs
5,317
mainloop(pyclockan analog/digital clock widget one of the first things always look for when exploring new computer interface is clock because spend so much time glued to computersit' essentially impossible for me to keep track of the time unless it is right there on the screen in front of me (and even thenit' iffythe next programpyclockimplements such clock widget in python it' not substantially different from the clock programs that you may be used to seeing on the window system because it is coded in pythonthoughthis one is both easily customized and fully portable among windowsthe window systemand macslike all the code in this in addition to advanced gui techniquesthis example demonstrates python math and time module tools quick geometry lesson before show you pyclockthoughlet me provide little background and confession quick--how do you plot points on circlethisalong with time formats and eventsturns out to be core concept in clock widget programs to draw an analog clock face on canvas widgetyou essentially need to be able to sketch circle--the clock face itself is composed of points on circleand the secondminuteand hour hands of the clock are really just lines from circle' center out to point on the circle digital clocks are simpler to drawbut not much to look at now the confessionwhen started writing pyclocki couldn' answer the last paragraph' opening question had utterly forgotten the math needed to sketch out points on circle (as had most of the professional software developers queried about this magic formulait happens after going unused for few decadessuch knowledge tends to be garbage collected finally was able to dust off few neurons long enough to code the plotting math neededbut it wasn' my finest intellectual hour +if you are in the same boati don' have space to teach geometry in depth herebut can show you one way to code the point-plotting formulas in python in simple terms before tackling the more complex task of implementing clocki wrote the plotter gui script shown in example - to focus on just the circle-plotting logic its point function is where the circle logic lives--it plots the ( ,ycoordinates of point on the circlegiven the relative point numberthe total number of points to be placed on the circleand the circle' radius (the distance from the circle' center to the points drawn upon itit first calculates the point' angle from the top by dividing by the +lest that make software engineers seem too doltishi should also note that have been called on repeatedly to teach python programming to physicistsall of whom had mathematical training well in advance of my ownand many of whom were still happily abusing fortran common blocks and go-tos specialization in modern society can make novices of us all pyclockan analog/digital clock widget
5,318
you've forgotten tooit' degrees around the whole circle ( if you plot points on circleeach is degrees from the lastor / python' standard math module gives all the required constants and functions from that point forward--pisineand cosine the math is really not too obscure if you study this long enough (in conjunction with your old geometry text if necessarythere are alternative ways to code the number crunchingbut 'll skip the details here (see the examples package for hintseven if you don' care about the maththoughcheck out example - ' circle function given the ( ,ycoordinates of point on the circle returned by pointit draws line from the circle' center out to the point and small rectangle around the point itself--not unlike the hands and points of an analog clock canvas tags are used to associate drawn objects for deletion before each plot example - pp \gui\clock\plottergui py plot circles on canvas import mathsys from tkinter import def point(tickrangeradius)angle tick ( rangeradiansperdegree math pi pointx introundradius math sin(angle radiansperdegree)pointy introundradius math cos(angle radiansperdegree)return (pointxpointydef circle(pointsradiuscenterxcenteryslow= )canvas delete('lines'canvas delete('points'for in range(points)xy point( + pointsradius- scaledxscaledy ( centerx)(centery ycanvas create_line(centerxcenteryscaledxscaledytag='lines'canvas create_rectangle(scaledx- scaledy- scaledx+ scaledy+ fill='red'tag='points'if slowcanvas update(def plotter() /trunc div circle(scalevar get()(width / )originxoriginycheckvar get()def makewidgets()global canvasscalevarcheckvar canvas canvas(width=widthheight=widthcanvas pack(side=topscalevar intvar(checkvar intvar(scale scale(label='points on circle'variable=scalevarfrom_= to= scale pack(side=leftcheckbutton(text='slow mode'variable=checkvarpack(side=leftbutton(text='plot'command=plotterpack(side=leftpadx= complete gui programs
5,319
width if len(sys argv= width int(sys argv[ ]originx originy width / makewidgets(mainloop(default widthheight width cmdline argsame as circle radius on default tk root need /trunc div the circle defaults to pixels wide unless you pass width on the command line given number of points on circlethis script marks out the circle in clockwise order every time you press plotby drawing lines out from the center to small rectangles at points on the circle' shape move the slider to plot different number of points and click the checkbox to make the drawing happen slow enough to notice the clockwise order in which lines and points are drawn (this forces the script to update the display after each line is drawnfigure - shows the result for plotting points with the circle width set to on the command lineif you ask for and points on the circlethe relationship to clock faces and hands starts becoming clearer figure - plottergui in action pyclockan analog/digital clock widget
5,320
this plotting script that print circle point coordinates to the stdout stream for reviewinstead of rendering them in gui see the plottertext py scripts in the clock' directory here is the sort of output they produce when plotting and points on circle that is points wide and highthe output format is simplypointnumber angle (xcoordinateycoordinateand assumes that the circle is centered at coordinate ( , ) ( ( - (- ( ( ( ( ( - ( - ( - (- - (- - (- (- (- ( numeric python tools if you do enough number crunching to have followed this section' abbreviated geometry lessonyou will probably also be interested in exploring the numpy numeric programming extension for python it adds things such as vector objects and advanced mathematical operationseffectively turning python into scientific/numeric programming tool that supports efficient numerical array computationsand it has been compared to matlab numpy has been used effectively by many organizationsincluding lawrence livermore and los alamos national labs--in many casesallowing python with numpy to replace legacy fortran code numpy must be fetched and installed separatelysee python' website for links on the webyou'll also find related numeric tools ( scipy)as well as visualization and animation tools ( pyopenglblendermayavtkand vpythonat this writingnumpy (like the many numeric packages that depend upon itis officially available for python onlybut version that supports both versions and is in early development release form besides the math modulepython itself also has built-in complex number type for engineering worka fixed-precision decimal type added in release and rational fraction type added in and see the library manual and python language fundamentals books such as learning python for details complete gui programs
5,321
the width and height of circle are always the same--the radius because tkinter canvas ( ,ycoordinates start at ( , in the upper-left cornerthe plotter gui must offset the circle' center point to coordinates (width/ width/ )--the origin point from which lines are drawn for instancein circlethe canvas center is ( , line to the -degree angle point on the right side of the circle runs from ( , to ( , )--the result of adding the ( , point coordinates plotted for the radius and angle line to the bottom at degrees runs from ( , to ( , after factoring in the ( ,- point plotted this point-plotting algorithm used by plotterguialong with few scaling constantsis at the heart of the pyclock analog display if this still seems bit muchi suggest you focus on the pyclock script' digital display implementation firstthe analog geometry plots are really just extensions of underlying timing mechanisms used for both display modes in factthe clock itself is structured as generic frame object that embeds digital and analog display objects and dispatches time change and resize events to both in the same way the analog display is an attached canvas that knows how to draw circlesbut the digital object is simply an attached frame with labels to show time components running pyclock apart from the circle geometry bitthe rest of pyclock is straightforward it simply draws clock face to represent the current time and uses widget after methods to wake itself up times per second to check whether the system time has rolled over to the next second on second rolloversthe analog secondminuteand hour hands are redrawn to reflect the new time (or the text of the digital display' labels is changedin terms of gui constructionthe analog display is etched out on canvasredrawn whenever the window is resizedand changes to digital format upon request pyclock also puts python' standard time module into service to fetch and convert system time information as needed for clock in briefthe ontimer method gets system time with time timea built-in tool that returns floating-point number giving seconds since the epoch--the point from which your computer counts time the time local time call is then used to convert epoch time into tuple that contains hourminuteand second valuessee the script and python library manual for additional details checking the system time times per second may seem intensebut it guarantees that the second hand ticks when it shouldwithout jerks or skips (after events aren' precisely timedit is not significant cpu drain on systems use on linux and windowspyclock uses negligible processor resources--what it does use is spent largely on screen updates in analog display modenot on after events ss ss the pydemos script of the preceding for instancelaunches seven clocks that run in the same processand all update smoothly on my (relatively slowwindows netbook laptop they together consume low single-digit percentage of the cpu' bandwidthand often less than the task manager pyclockan analog/digital clock widget
5,322
points on the clock' circle are redrawn only at startup and on window resizes figure - shows the default initial pyclock display format you get when the file clock py is run directly figure - pyclock default analog display the clock hand lines are given arrows at their endpoints with the canvas line object' arrow and arrowshape options the arrow option can be firstlastnoneor boththe arrowshape option takes tuple giving the length of the arrow touching the lineits overall lengthand its width like pyviewpyclock also uses the widget pack_forget and pack methods to dynamically erase and redraw portions of the display on demand ( in response to bound eventsclicking on the clock with left mouse button changes its display to digital by erasing the analog widgets and drawing the digital interfaceyou get the simpler display captured in figure - figure - pyclock goes digital this digital display form is useful if you want to conserve real estate on your computer screen and minimize pyclock cpu utilization (it incurs very little screen update overheadleft-clicking on the clock again changes back to the analog display the analog complete gui programs
5,323
packed at any given time right mouse click on the clock in either display mode shows or hides an attached label that gives the current date in simple text form figure - shows pyclock running with an analog displaya clicked-on date labeland centered photo image object (this is clock style started by the pygadgets launcher)figure - pyclock extended display with an image the image in the middle of figure - is added by passing in configuration object with appropriate settings to the pyclock object constructor in factalmost everything about this display can be customized with attributes in pyclock configuration objects--hand colorsclock tick colorscenter photosand initial size because pyclock' analog display is based upon manually sketched figure on canvasit has to process window resize events itselfwhenever the window shrinks or expandsthe clock face has to be redrawn and scaled for the new window size to catch screen resizesthe script registers for the event with bindsurprisinglythis isn' top-level window manager event like the close button as you expand pyclockthe clock face gets bigger with the window--try expandingshrinkingand maximizing the clock window on your computer because the clock face is plotted in square coordinate systempyclock always expands in equal horizontal and vertical proportionsthoughif you simply make the window only wider or tallerthe clock is unchanged added in the third edition of this book is countdown timer featurepress the "sor "mkey to pop up simple dialog for entering the number of seconds or minutes for the countdownrespectively once the countdown expiresthe pop up in figure - appears and fills the entire screen on windows sometimes use this in pyclockan analog/digital clock widget
5,324
classes teach to remind myself and my students when it' time to move on (the effect is more striking when this pop up is projected onto an entire wall!finallylike pyeditpyclock can be run either standalone or attached to and embedded in other guis that need to display the current time when standalonethe windows module from the preceding (example - is reused here to get window icontitleand quit pop up for free to make it easy to start preconfigured clocksa utility module called clockstyles provides set of clock configuration objects you can importsubclass to extendand pass to the clock constructorfigure - shows few of the preconfigured clock styles and sizes in actionticking away in sync run clockstyles py (or select pyclock from pydemoswhich does the sameto recreate this timely scene on your computer each of these clocks uses after events to check for system-time rollover times per second when run as top-level windows in the same processall receive timer event from the same event loop when started as independent programseach has an event loop of its own either waytheir second hands sweep in unison each second pyclock source code all of the pyclock source code lives in one fileexcept for the precoded configuration style objects if you study the code at the bottom of the file shown in example - you'll notice that you can either make clock object with configuration object passed in or specify configuration options by command-line arguments such as the following (in which casethe script simply builds configuration object for you) :\pp \gui\clockclock py -bg gold -sh brown -size complete gui programs
5,325
more generallyyou can run this file directly to start clock with or without argumentsimport and make its objects with configuration objects to get more custom displayor import and attach its objects to other guis for instancepygadgets in runs this file with command-line options to tailor the display example - pp \gui\clock\clock py ""##############################################################################pyclock clock gui in python/tkinter with both analog and digital display modesa pop-up date labelclock face imagesgeneral resizingetc may be run both standaloneor embedded (attachedin other guis that need clock new in / keys set seconds/minutes timer for pop-up msgwindow icon new in updated to run under python ( no longer supported##############################################################################""from tkinter import from tkinter simpledialog import askinteger import mathtimesys ##############################################################################option configuration classes ##############################################################################pyclockan analog/digital clock widget
5,326
defaults--override in instance or subclass size bgfg 'beige''brownhhmhshcog 'black''navy''blue''redpicture none width=height facetick colors clock handscenter face photo file class photoclockconfig(clockconfig)sample configuration size picture /gifs/ora-pp gifbghhmh 'white''blue''orange##############################################################################digital display object ##############################################################################class digitaldisplay(frame)def __init__(selfparentcfg)frame __init__(selfparentself hour label(selfself mins label(selfself secs label(selfself ampm label(selffor label in self hourself minsself secsself ampmlabel config(bd= relief=sunkenbg=cfg bgfg=cfg fglabel pack(side=lefttbdcould expandand scale font on resize def onupdate(selfhourminssecsampmcfg)mins str(minszfill( self hour config(text=str(hour)width= self mins config(text=str(mins)width= self secs config(text=str(secs)width= self ampm config(text=str(ampm)width= or '% dx def onresize(selfnewwidthnewheightcfg)pass nothing to redraw here ##############################################################################analog display object ##############################################################################class analogdisplay(canvas)def __init__(selfparentcfg)canvas __init__(selfparentwidth=cfg sizeheight=cfg sizebg=cfg bgself drawclockface(cfgself hourhand self minshand self secshand self cog none def drawclockface(selfcfg)if cfg picture complete gui programs on start and resize draw ovalspicture
5,327
self image photoimage(file=cfg picturebkground exceptself image bitmapimage(file=cfg picturesave ref imgx (cfg size self image width()/ center it imgy (cfg size self image height()/ /div self create_image(imgx+ imgy+ anchor=nwimage=self imageoriginx originy radius cfg size / /div for in range( )xy self point( radius- originxoriginyself create_rectangle( - - + + fill=cfg fgmins for in range( )xy self point( radius- originxoriginyself create_rectangle( - - + + fill=cfg fghours self ampm self create_text( anchor=nwfill=cfg fgdef point(selftickunitsradiusoriginxoriginy)angle tick ( unitsradiansperdegree math pi pointx introundradius math sin(angle radiansperdegree)pointy introundradius math cos(angle radiansperdegree)return (pointx originx+ )(originy+ pointydef onupdate(selfhourminssecsampmcfg)on timer callback if self cogredraw handscog self delete(self cogself delete(self hourhandself delete(self minshandself delete(self secshandoriginx originy radius cfg size / div hour hour (mins hxhy self point(hour (radius )originxoriginymxmy self point(mins (radius )originxoriginysxsy self point(secs (radius )originxoriginyself hourhand self create_line(originxoriginyhxhywidth=(cfg size )arrow='last'arrowshape=( , , )fill=cfg hhself minshand self create_line(originxoriginymxmywidth=(cfg size )arrow='last'arrowshape=( , , )fill=cfg mhself secshand self create_line(originxoriginysxsywidth= arrow='last'arrowshape=( , , )fill=cfg shcogsz cfg size self cog self create_oval(originx-cogszoriginy+cogszoriginx+cogszoriginy-cogszfill=cfg cogself dchars(self ampm endself insert(self ampmendampmdef onresize(selfnewwidthnewheightcfg)newsize min(newwidthnewheight#print('analog onresize'cfg size+ newsizeif newsize !cfg size+ cfg size newsize- self delete('all'pyclockan analog/digital clock widget
5,328
onupdate called next ##############################################################################clock composite object ##############################################################################checkspersec second change timer class clock(frame)def __init__(selfconfig=clockconfigparent=none)frame __init__(selfparentself cfg config self makewidgets(parentchildren are packed but self labelon clients pack or grid me self display self digitaldisplay self lastsec self lastmin - self countdownseconds self onswitchmode(noneself ontimer(def makewidgets(selfparent)self digitaldisplay digitaldisplay(selfself cfgself analogdisplay analogdisplay(selfself cfgself datelabel label(selfbd= bg='red'fg='blue'parent bind(''self onswitchmodeparent bind(''self ontogglelabelparent bind(''self onresizeparent bind(''self oncountdownsecparent bind(''self oncountdownmindef onswitchmode(selfevent)self display pack_forget(if self display =self analogdisplayself display self digitaldisplay elseself display self analogdisplay self display pack(side=topexpand=yesfill=bothdef ontogglelabel(selfevent)self labelon + if self labelon self datelabel pack(side=bottomfill=xelseself datelabel pack_forget(self update(def onresize(selfevent)if event widget =self displayself display onresize(event widthevent heightself cfgdef ontimer(self)secssinceepoch time time(timetuple time localtime(secssinceepochhourminsec timetuple[ : complete gui programs
5,329
self lastsec sec ampm ((hour > and 'pm'or 'am hour (hour or self display onupdate(hourminsecampmself cfgself datelabel config(text=time ctime(secssinceepoch)self countdownseconds - if self countdownseconds = self oncountdownexpire(countdown timer self after( /checkspersecself ontimerrun times per second /trunc int div def oncountdownsec(selfevent)secs askinteger('countdown''seconds?'if secsself countdownseconds secs def oncountdownmin(selfevent)secs askinteger('countdown''minutes'if secsself countdownseconds secs def oncountdownexpire(self)caveatonly one activeno progress indicator win toplevel(msg button(wintext='timer expired!'command=win destroymsg config(font=('courier' 'normal')fg='white'bg='navy'msg config(padx= pady= msg pack(expand=yesfill=bothwin lift(raise above siblings if sys platform[: ='win'full screen on windows win state('zoomed'##############################################################################standalone clocks ##############################################################################appname 'pyclock use new custom tktoplevel for iconsetc from pp gui tools windows import popupwindowmainwindow class clockpopup(popupwindow)def __init__(selfconfig=clockconfigname='')popupwindow __init__(selfappnamenameclock clock(configselfclock pack(expand=yesfill=bothclass clockmain(mainwindow)def __init__(selfconfig=clockconfigname='')mainwindow __init__(selfappnamenameclock clock(configselfclock pack(expand=yesfill=bothb/ compatmanual window borderspassed-in parent pyclockan analog/digital clock widget
5,330
def __init__(selfconfig=clockconfigparent=nonename='')clock __init__(selfconfigparentself pack(expand=yesfill=bothtitle appname if nametitle appname name self master title(titlemaster=parent or default self master protocol('wm_delete_window'self quit##############################################################################program run ##############################################################################if __name__ ='__main__'def getoptions(configargv)for attr in dir(clockconfig)fill default config objtryfrom "-attr valcmd args ix argv index('-attrwill skip __x__ internals exceptcontinue elseif ix in range( len(argv)- )if type(getattr(clockconfigattr)=intsetattr(configattrint(argv[ix+ ])elsesetattr(configattrargv[ix+ ]#config photoclockconfig(config clockconfig(if len(sys argv> getoptions(configsys argvclock py -size -bg 'blue#myclock clockwindow(configtk()parent is tk root if standalone #myclock clockpopup(clockconfig()'popup'myclock clockmain(configmyclock mainloop(and finallyexample - shows the module that is actually run from the pydemos launcher script--it predefines handful of clock styles and runs seven of them at onceattached to new top-level windows for demo effect (though one clock per screen is usually enough in practiceeven for me!example - pp \gui\clock\clockstyles py precoded clock configuration styles from clock import from tkinter import mainloop gifdir /gifs/if __name__ ='__main__'from sys import argv if len(argv gifdir argv[ '/ complete gui programs
5,331
picturebgfg gifdir 'ora-pp gif''navy''greenclass ppclocksmall(clockconfig)size picture gifdir 'ora-pp gifbgfghhmh 'white''red''blue''orangeclass gilliganclock(clockconfig)size picture gifdir 'gilligan gifbgfghhmh 'black''white''green''yellowclass lp eclock(gilliganclock)size picture gifdir 'ora-lp gifbg 'navyclass lp eclocksmall(lp eclock)sizefg 'orangeclass pyref eclock(clockconfig)sizepicture gifdir 'ora-pyref gifbgfghh 'black''gold''brownclass greyclock(clockconfig)bgfghhmhsh 'grey''black''black''black''whiteclass pinkclock(clockconfig)bgfghhmhsh 'pink''yellow''purple''orange''yellowclass pythonpoweredclock(clockconfig)bgsizepicture 'white' gifdir 'pythonpowered gifif __name__ ='__main__'root tk(for configclass in clockconfigppclockbig#ppclocksmalllp eclocksmall#gilliganclockpyref eclockgreyclockpinkclockpythonpoweredclock ]clockpopup(configclassconfigclass __name__button(roottext='quit clocks'command=root quitpack(root mainloop(running this script creates the multiple clock display of figure - its configurations support numerous optionsjudging from the seven clocks on the displaythoughit' time to move on to our last example pyclockan analog/digital clock widget
5,332
finallya bit of fun to close out this our last examplepytoeimplements an artificially intelligent tic-tac-toe (sometimes called "naughts and crosses"gameplaying program in python most readers are probably familiar with this simple gameso won' dwell on its details in shortplayers take turns marking board positionsin an attempt to occupy an entire rowcolumnor diagonal the first player to fill such pattern wins in pytoeboard positions are marked with mouse clicksand one of the players is python program the game board itself is displayed with simple tkinter guiby defaultpytoe builds game board (the standard tic-tac-toe setup)but it can be configured to build and play an arbitrary game when it comes time for the computer to select moveartificial intelligence (aialgorithms are used to score potential moves and search tree of candidate moves and countermoves this is fairly simple problem as gaming programs goand the heuristics used to pick moves are not perfect stillpytoe is usually smart enough to spot wins few moves in advance of the user running pytoe pytoe' gui is implemented as frame of expandable packed labelswith mouse-click bindings on the labels to catch user moves the label' text is configured with the player' mark after each movecomputer or user the guimaker class we coded earlier in the prior (example - is also reused here again to add simple menu bar at the top (but no toolbar is drawn at the bottombecause pytoe leaves its format descriptor emptyby defaultthe user' mark is "xand pytoe' is " figure - shows pytoe run from pygadgets with its status pop-up dialogon the verge of beating me one of two ways figure - shows pytoe' help pop-up dialogwhich lists its command-line configuration options you can specify colors and font sizes for board labelsthe player who moves firstthe mark of the user ("xor " ")the board size (to override the default)and the move selection strategy for the computer ( "minimaxperforms move tree search to spot wins and lossesand "expert and "expert use static scoring heuristics functionsthe ai gaming techniques used in pytoe are cpu intensiveand some computer move selection schemes take longer than othersbut their speed varies mostly with the speed of your computer move selection delays are fractions of second long on my machine for game boardfor all "-modemove-selection strategy options figure - shows an alternative pytoe configuration (shown running its top-level script directly with no arguments)just after it beat me despite the scenes captured for this bookunder some move selection optionsi do still win once in while in complete gui programs
5,333
larger boards and more complex gamespytoe' move selection algorithms become even more useful pytoe source code (externalpytoe is big system that assumes some ai background knowledge and doesn' really demonstrate anything new in terms of guis moreoverit was written for python over decade agoand though ported to for this editionsome of it might be better recoded from scratch today partly because of thatbut mostly because have page limit for this booki' going to refer you to the book' examples distribution package for its source code instead of listing it here please see these two files in the examples distribution for pytoe implementation detailspp \ai\tictactoe\tictactoe py top-level wrapper script pp \ai\tictactoe\tictactoe_lists py the meat of the implementation pytoea tic-tac-toe game widget
5,334
if you do lookthoughprobably the best hint can give you is that the data structure used to represent board state is the crux of the matter that isif you understand the way boards are modeledthe rest of the code comes naturally for instancethe lists-based variant uses list-of-lists to represent the board' statealong with simple dictionary of entry widgets for the gui indexed by board coordinates clearing the board after game is simply matter of clearing the underlying data structuresas shown in this code excerpt from the examples named earlier complete gui programs
5,335
def clearboard(self)for rowcol in self label keys()self board[row][colempty self label[(rowcol)config(text='similarlypicking moveat least in random modeis simply matter of picking nonempty slot in the board array and storing the machine' mark there and in the gui (degree is the board' size)def machinemove(self)rowcol self pickmove(self board[row][colself machinemark self label[(rowcol)config(text=self machinemarkdef pickmove(self)empties [for row in self degreefor col in self degreeif self board[row][col=emptyempties append((rowcol)return random choice(emptiesfinallychecking for an end-of-game state boils down to inspecting rowscolumnsand diagonals in the two-dimensional list-of-lists board in this schemepytoea tic-tac-toe game widget
5,336
board board or self board for row in boardif empty in rowreturn return none emptydraw or win def checkwin(selfmarkboard=none)board board or self board for row in boardif row count(mark=self degreereturn for col in range(self degree)for row in boardif row[col!markbreak elsereturn for row in range(self degree)col row if board[row][col!markbreak elsereturn for row in range(self degree)col (self degree- row if board[row][col!markbreak elsereturn check across check down check diag row =col check diag row+col degree- def checkfinish(self)if self checkwin(self usermark)outcome "you've won!elif self checkwin(self machinemark)outcome ' win again :-)elif self checkdraw()outcome 'looks like drawother move-selection code mostly just performs other kinds of analysis on the board data structure or generates new board states to search tree of moves and countermoves you'll also find relatives of these files in the same directory that implements alternative search and move-scoring schemesdifferent board representationsand so on for additional background on game scoring and searches in generalconsult an ai text it' fun stuffbut it' too specialized to cover well in this book where to go from here this concludes the gui section of this bookbut this is not an end to the book' gui coverage if you want to learn more about guisbe sure to see the tkinter examples that appear later in this book and are described at the start of this pymailguipycalcand the mostly external pyform and pytree provide additional gui case complete gui programs
5,337
that run in web browsers-- very different conceptbut another option for interface design keep in mindtoothat even if you don' see gui example in this book that looks very close to one you need to programyou've already met all the building blocks constructing larger guis for your application is really just matter of laying out hierarchical composites of the widgets presented in this part of the text for instancea complex display might be composed as collection of radio buttonslistboxesscalestext fieldsmenusand so on--all arranged in frames or grids to achieve the desired appearance pop-up top-level windowsas well as independently run gui programs linked with inter-process communication (ipcmechanismssuch as pipessignalsand socketscan further supplement complex graphical interface moreoveryou can implement larger gui components as python classes and attach or extend them anywhere you need similar interface devicesee pyedit' role in pyview and pymailgui for prime example with little creativitytkinter' widget set and python support virtually unlimited number of layouts beyond this booksee the tkinter documentation overview in the books department at python' website at if you catch the tkinter bugi want to again recommend downloading and experimenting with the packages introduced in --especially pmwpiltixand ttk (tix and ttk are standard part of python todaysuch extensions add additional tools to the tkinter arsenal that can make your guis more sophisticatedwith minimal coding where to go from here
5,338
internet programming this part of the book explores python' role as language for programming internetbased applicationsand its library tools that support this role along the waysystem and gui tools presented earlier in the book are put to use as well because this is popular python domain here cover all fronts this introduces internet concepts and optionspresents python low-level network tools such as socketsand covers client and server basics this shows you how your scripts can use python to access common clientside network protocols like ftpemailhttpand more this uses the client-side email tools covered in the prior as well as the gui techniques of the prior partto implement full-featured email client this introduces the basics of python server-side common gateway interface (cgiscripts-- kind of program used to implement interactive websites this demonstrates python website techniques by implementing webbased email tool on serverin part to compare and contrast with ' nonweb approach although they are outside this book' scope also provides brief overviews of more advanced python internet tools best covered in follow-up resourcessuch as jythondjangoapp enginezopepsppyjamasand htmlgen hereyou'll learn the fundamentals needed to use such tools when you're ready to step up along the waywe'll also put general programming concepts such as object-oriented programming (oopand code refactoring and reuse to work here as we'll seepythonguisand networking are powerful combination
5,339
network scripting "tune inlog onand drop outover the years since this book was first publishedthe internet has virtually exploded onto the mainstream stage it has rapidly grown from simple communication device used primarily by academics and researchers into medium that is now nearly as pervasive as the television and telephone social observers have likened the internet' cultural impact to that of the printing pressand technical observers have suggested that all new software development of interest occurs only on the internet naturallytime will be the final arbiter for such claimsbut there is little doubt that the internet is major force in society and one of the main application contexts for modern software systems the internet also happens to be one of the primary application domains for the python programming language in the decade and half since the first edition of this book was writtenthe internet' growth has strongly influenced python' tool set and roles given python and computer with socket-based internet connection todaywe can write python scripts to read and send email around the worldfetch web pages from remote sitestransfer files by ftpprogram interactive websitesparse html and xml filesand much moresimply by using the internet modules that ship with python as standard tools in factcompanies all over the world dogoogleyoutubewalt disneyhewlettpackardjpland many others rely on python' standard tools to power their websites for examplethe google search engine--widely credited with making the web usable--makes extensive use of python code the youtube video server site is largely implemented in python and the bittorrent peer-to-peer file transfer system--written in python and downloaded by tens of millions of users--leverages python' networking skills to share files among clients and remove some server bottlenecks many also build and manage their sites with larger python-based toolkits for instancethe zope web application server was an early entrant to the domain and is itself written and customizable in python others build sites with the plone content management
5,340
python to script java web applications with jython (formerly known as jpython)-- system that compiles python programs to java bytecodeexports java libraries for use in python scriptsand allows python code to serve as web applets downloaded and run in browser in more recent yearsnew techniques and systems have risen to prominence in the web sphere for examplexml-rpc and soap interfaces for python have enabled web service programmingframeworks such as google app enginedjangoand turbogears have emerged as powerful tools for constructing websitesthe xml package in python' standard libraryas well as third-party extensionsprovides suite of xml processing toolsand the ironpython implementation provides seamless net/mono integration for python code in much the same way jython leverages java libraries as the internet has grownso too has python' role as an internet tool python has proven to be well suited to internet scripting for some of the very same reasons that make it ideal in other domains its modular design and rapid turnaround mix well with the intense demands of internet development in this part of the bookwe'll find that python does more than simply support internet scriptingit also fosters qualities such as productivity and maintainability that are essential to internet projects of all shapes and sizes internet scripting topics internet programming entails many topicsso to make the presentation easier to digesti've split this subject over the next five of this book here' this part' rundownthis introduces internet fundamentals and explores socketsthe underlying communications mechanism of the internet we met sockets briefly as ipc tools in and again in gui use case in but here we will study them in the depth afforded by their broader networking roles covers the fundamentals of client-side scripting and internet protocols herewe'll explore python' standard support for ftpemailhttpnntpand more presents larger client-side case studypymailguia full-featured email client discusses the fundamentals of server-side scripting and website construction we'll study basic cgi scripting techniques and concepts that underlie most of what happens in the web presents larger server-side case studypymailcgia full-featured webmail site each assumes you've read the previous onebut you can generally skip aroundespecially if you have prior experience in the internet domain since these network scripting
5,341
few more details about what we'll be studying what we will cover in conceptual termsthe internet can roughly be thought of as being composed of multiple functional layerslow-level networking layers mechanisms such as the tcp/ip transport mechanismwhich deal with transferring bytes between machinesbut don' care what they mean sockets the programmer' interface to the networkwhich runs on top of physical networking layers like tcp/ip and supports flexible client/server models in both ipc and networked modes higher-level protocols structured internet communication schemes such as ftp and emailwhich run on top of sockets and define message formats and standard addresses server-side web scripting application models such as cgiwhich define the structure of communication between web browsers and web serversalso run on top of socketsand support the notion of web-based programs higher-level frameworks and tools third-party systems such as djangoapp enginejythonand pyjamaswhich leverage sockets and communication protocolstoobut address specific techniques or larger problem domains this book covers the middle three tiers in this list--socketsthe internet protocols that run on themand the cgi model of web-based conversations what we learn here will also apply to more specific toolkits in the last tier abovebecause they are all ultimately based upon the same internet and web fundamentals more specificallyin this and the next our main focus is on programming the second and third layerssockets and higher-level internet protocols we'll start this at the bottomlearning about the socket model of network programming sockets aren' strictly tied to internet scriptingas we saw in ' ipc examplesbut they are presented in full here because this is one of their primary roles as we'll seemost of what happens on the internet happens through socketswhether you notice or not after introducing socketsthe next two make their way up to python' clientside interfaces to higher-level protocols--things like email and ftp transferswhich run on top of sockets it turns out that lot can be done with python on the client aloneand and will sample the flavor of python client-side scripting finallythe last two in this part of the book then move on to present server-side "tune inlog onand drop out
5,342
browser what we won' cover now that 've told you what we will cover in this booki also want to be clear about what we won' cover like tkinterthe internet is vast topicand this part of the book is mostly an introduction to its core concepts and an exploration of representative tasks because there are so many internet-related modules and extensionsthis book does not attempt to serve as an exhaustive survey of the domain even in just python' own tool setthere are simply too many internet modules to include each in this text in any sort of useful fashion moreoverhigher-level tools like djangojythonand app engine are very large systems in their own rightand they are best dealt with in more focused documents because dedicated books on such topics are now availablewe'll merely scratch their surfaces here with brief survey later in this this book also says almost nothing about lower-level networking layers such as tcp/ip if you're curious about what happens on the internet at the bit-and-wire levelconsult good networking text for more details in other wordsthis part is not meant to be an exhaustive reference to internet and web programming with python-- topic which has evolved between prior editions of this bookand will undoubtedly continue to do so after this one is published insteadthe goal of this part of the book is to serve as tutorial introduction to the domain to help you get startedand to provide context and examples which will help you understand the documentation for tools you may wish to explore after mastering the fundamentals here other themes in this part of the book like the prior parts of the bookthis one has other agendastoo along the waythis part will also put to work many of the operating-system and gui interfaces we studied in parts ii and iii ( processesthreadssignalsand tkinterwe'll also get to see the python language applied in realistically scaled programsand we'll investigate some of the design choices and challenges that the internet presents that last statement merits few more words internet scriptinglike guisis one of the "sexierapplication domains for python as in gui workthere is an intangible but instant gratification in seeing python internet program ship information all over the world on the other handby its very naturenetwork programming can impose speed overheads and user interface limitations though it may not be fashionable stance these dayssome applications are still better off not being deployed on the web traditional "desktopgui like those of part iiifor examplecan combine the featurerichness and responsiveness of client-side libraries with the power of network access on the other handweb-based applications offer compelling benefits in portability and network scripting
5,343
nonweb architectures in factthe larger pymailgui and pymailcgi examples we'll explore are intended in part to serve this purpose the internet is also considered by many to be something of an ultimate proof of concept for open source tools indeedmuch of the net runs on top of large number of such toolssuch as pythonperlthe apache web serverthe sendmail programmysqland linux moreovernew tools and technologies for programming the web sometimes seem to appear faster than developers can absorb them the good news is that python' integration focus makes it natural in such heterogeneous world todaypython programs can be installed as client-side and server-side toolsused as applets and servlets in java applicationsmixed into distributed object systems like corbasoapand xml-rpcintegrated into ajax-based applicationsand much more in more general termsthe rationale for using python in the internet domain is exactly the same as in any other--python' emphasis on qualityproductivityportabilityand integration makes it ideal for writing internet programs that are openmaintainableand delivered according to the ever-shrinking schedules in this field running examples in this part of the book internet scripts generally imply execution contexts that earlier examples in this book have not that isit usually takes bit more to run programs that talk over networks here are few pragmatic notes about this part' examplesup frontyou don' need to download extra packages to run examples in this part of the book all of the examples we'll see are based on the standard set of internet-related modules that come with python and are installed in python' library directory you don' need state-of-the-art network link or an account on web server to run the socket and client-side examples in this part although some socket examples will be shown running remotelymost can be run on single local machine client-side examples that demonstrate protocol like ftp require only basic internet accessand email examples expect just pop and smtp capable servers you don' need an account on web server machine to run the server-side scripts in later they can be run by any web browser you may need such an account to change these scripts if you store them remotelybut not if you use locally running web server as we will in this book there is even common acronym for this todaylampfor the linux operating systemthe apache web serverthe mysql database systemand the pythonperland php scripting languages it' possibleand even very commonto put together an entire enterprise-level web server with open source tools python users would probably also like to include systems like zopedjangowebwareand cherrypy in this listbut the resulting acronym might be bit of stretch "tune inlog onand drop out
5,344
opens an internet connection (with the socket module or one of the internet protocol modules)python will happily use whatever internet link exists on your machinebe that dedicated linea dsl lineor simple modem for instanceopening socket on windows pc automatically initiates processing to create connection to your internet provider if needed moreoveras long as your platform supports socketsyou probably can run many of the examples here even if you have no internet connection at all as we'll seea machine name localhost or "(an empty stringusually means the local computer itself this allows you to test both the client and the server sides of dialog on the same computer without connecting to the net for exampleyou can run both socket-based clients and servers locally on windows pc without ever going out to the net in other wordsyou can likely run the programs here whether you have way to connect to the internet or not some later examples assume that particular kind of server is running on server machine ( ftppopsmtp)but client-side scripts themselves work on any internet-aware machine with python installed server-side examples in and require moreto develop cgi scriptsyou'll need to either have web server account or run web server program locally on your own computer (which is easier than you may think--we'll learn how to code simple one in python in advanced third-party systems like jython and zope must be downloaded separatelyof coursewe'll peek at some of these briefly in this but defer to their own documentation for more details in the beginning there was grail besides creating the python languageguido van rossum also wrote world wide web browser in python years agonamed (appropriately enoughgrail grail was partly developed as demonstration of python' capabilities it allows users to browse the web much like firefox or internet explorerbut it can also be programmed with grail applets--python/tkinter programs downloaded from server when accessed and run on the client by the browser grail applets work much like java applets in more widespread browsers (more on applets in the next sectionthough it was updated to run under recent python releases as was finishing this editiongrail is no longer under active development todayand it is mostly used for research purposes (indeedthe netscape browser was counted among its contemporariesneverthelesspython still reaps the benefits of the grail projectin the form of rich set of internet tools to write full-featured web browseryou need to support wide variety of internet protocolsand guido packaged support for all of these as standard library modules that were eventually shipped with the python language because of this legacypython now includes standard support for usenet news (nntp)email processing (popsmtpimap)file transfers (ftp)web pages and interactions (httpurlshtmlcgi)and other commonly used protocols such as telnet network scripting
5,345
associated library module since grailadditional tools have been added to python' library for parsing xml filesopenssl secure socketsand more but much of python' internet support can be traced back to the grail browser--another example of python' support for code reuse at work at this writingyou can still find the grail by searching for "grail web browserat your favorite web search engine python internet development options although many are outside our scope herethere are variety of ways that python programmers script the web just as we did for guisi want to begin with quick overview of some of the more popular tools in this domain before we jump into the fundamentals networking tools as we'll see in this python comes with tools the support basic networkingas well as implementation of custom types of network servers this includes socketsbut also the select call for asynchronous serversas well as higher-order and pre-coded socket server classes standard library modules socketselectand socketserver support all these roles client-side protocol tools as we'll see in the next python' internet arsenal also includes canned support for the client side of most standard internet protocols--scripts can easily make use of ftpemailhttptelnetand more especially when wedded to desktop guis of the sort we met in the preceding part of this bookthese tools open the door to full-featured and highly responsive web-aware applications server-side cgi scripting perhaps the simplest way to implement interactive website behaviorcgi scripting is an application model for running scripts on servers to process form datatake action based upon itand produce reply pages we'll use it later in this part of the book it' supported by python' standard library directlyis the basis for much of what happens on the weband suffices for simpler site development tasks raw cgi scripting doesn' by itself address issues such as cross-page state retention and concurrent updatesbut cgi scripts that use devices like cookies and database systems often can web frameworks and clouds for more demanding web workframeworks can automate many of the low-level details and provide more structured and powerful techniques for dynamic site implementation beyond basic cgi scriptsthe python world is flush with third-party web frameworks such as django-- high-level framework that encourages rapid development and cleanpragmatic design and includes dynamic database access python internet development options
5,346
computingframework that provides enterprise-level tools for use in python scripts and allows sites to leverage the capacity of google' web infrastructureand turbo gears--an integrated collection of tools including javascript librarya template systemcherrypy for web interactionand sqlobject for accessing databases using python' class model also in the framework category are zope--an open source web application server and toolkitwritten in and customizable with pythonin which websites are implemented using fundamentally object-oriented modelplone-- zope-based website builder which provides workflow model (called content management systemthat allows content producers to add their content to siteand other popular systems for website constructionincluding pylonsweb pycherrypyand webware many of these frameworks are based upon the now widespread mvc (model-viewcontrollerstructureand most provide state retention solutions that wrap database storage some make use of the orm (object relational mappingmodel we'll meet in the next part of the bookwhich superimposes python' classes onto relational database tablesand zope stores objects in your site in the zodb object-oriented database we'll study in the next part as well rich internet applications (revisiteddiscussed at the start of newer and emerging "rich internet application(riasystems such as flexsilverlightjavafxand pyjamas allow user interfaces implemented in web browsers to be much more dynamic and functional than html has traditionally allowed these are client-side solutionsbased generally upon ajax and javascriptwhich provide widget sets that rival those of traditional "desktopguis and provide for asynchronous communication with web servers according to some observerssuch interactivity is major component of the "web model ultimatelythe web browser is "desktopgui applicationtooalbeit one which is very widely available and which can be generalized with ria techniques to serve as platform for rendering other guisusing software layers that do not rely on particular gui library in effectrias turn web browsers into extendable guis at least that' their goal today compared to traditional guisrias gain some portability and deployment simplicityin exchange for decreased performance and increased software stack complexity moreovermuch as in the gui realmthere are already competing ria toolkits today which may add dependencies and impact portability unless pervasive frontrunner appearsusing ria application may require an install stepnot unlike desktop applications stay tunedthoughlike the web at largethe ria story is still work in progress the emerging html standardfor instancewhile likely not to become prevalent for some years to comemay obviate the need for ria browser plug-ins eventually network scripting
5,347
xml-rpc is technology that provides remote procedural calls to components over networks it routes requests over the http protocol and ships data back and forth packaged as xml text to clientsweb servers appear to be simple functionswhen function calls are issuedpassed data is encoded as xml and shipped to remote servers using the web' http transport mechanism the net effect is to simplify the interface to web servers in client-side programs more broadlyxml-rpc fosters the notion of web services--reusable software components that run on the web--and is supported by python' xmlrpc client modulewhich handles the client side of this protocoland xmlrcp serverwhich provides tools for the server side soap is similar but generally heavier web services protocolavailable to python in the third-party soapy and zsi packagesamong others corba orbs an earlier but comparable technologycorba is an architecture for distributed programmingin which components communicate across network by routing calls through an object request broker (orbpython support for corba is available in the third-party omniorb packageas well as the (still available though not recently maintainedilu system java and netjython and ironpython we also met jython and ironpython briefly at the start of in the context of guis by compiling python script to java bytecodejython also allows python scripts to be used in any context that java programs can this includes weboriented rolessuch as applets stored on the server but run on the client when referenced within web pages the ironpython system also mentioned in similarly offers web-focused optionsincluding access to the silverlight ria framework and its moonlight implementation in the mono system for linux screen scrapingxml and html parsing tools though not technically tied to the internetxml text often appears in such roles because of its other rolesthoughwe'll study python' basic xml parsing supportas well as third-party extensions to itin the next part of this bookwhen we explore python' text processing toolkit as we'll seepython' xml package comes with support for domsaxand elementtree style xml parsingand the open source domain provides extensions for xpath and much more python' html parser library module also provides html-specific parserwith model not unlike that of xml' sax technique such tools can be used in screen scraping rolesto extract content of web pages fetched with urllib request tools windows com and dcom the pywin package allows python scripts to communicate via com on windows to perform feats such as editing word documents and populating excel spreadsheets (additional tools support excel document processingthough not related to the internet itself (and being arguably upstaged by net in recent years)python internet development options
5,348
other tools other tools serve more specific roles among this crowd are mod_python-- system which optimizes the execution of python server-scripts in the apache web servertwisted--an asynchronousevent-drivennetworking framework written in pythonwith support for large number of network protocols and with precoded implementations of common network servershtmlgen-- lightweight tool that allows html code to be generated from tree of python objects that describes web pageand python server pages (psp)-- server-side templating technology that embeds python code inside htmlruns it with request context to render part of reply pageand is strongly reminiscent of phpaspand jsp as you might expect given the prominence of the webthere are more internet tools for python than we have space to discuss here for more on this frontsee the pypi website at are implemented using python' internet tools themselvesagainthe goal of this book is to cover the fundamentals in an in-depth wayso that you'll have the context needed to use tools like some of those above wellwhen you're ready to graduate to more comprehensive solutions as we'll seethe basic model of cgi scripting we'll meet here illustrates the mechanisms underlying all web developmentwhether it' implemented by bare-bones scriptsor advanced frameworks because we must walk before we can run wellthoughlet' start at the bottom hereand get handle on what the internet really is the internet today rests upon rich software stackwhile tools can hide some of its complexityprogramming it skillfully still requires knowledge of all its layers as we'll seedeploying python on the webespecially with higher-order web frameworks like those listed aboveis only possible because we truly are "surfing on the shoulders of giants plumbing the internet unless you've been living in cave for the last decade or twoyou are probably already familiar with the internetat least from user' perspective functionallywe use it as communication and information mediumby exchanging emailbrowsing web pagestransferring filesand so on technicallythe internet consists of many layers of abstraction and devices--from the actual wires used to send bits across the world to the web browser that grabs and renders those bits into textgraphicsand audio on your computer in this bookwe are primarily concerned with the programmer' interface to the internet thistooconsists of multiple layerssocketswhich are programmable interfaces to the low-level connections between machinesand standard protocolswhich add network scripting
5,349
in the abstract before jumping into programming details the socket layer in simple termssockets are programmable interface to connections between programspossibly running on different computers of network they allow data formatted as byte strings to be passed between processes and machines sockets also form the basis and low-level "plumbingof the internet itselfall of the familiar higher-level net protocolslike ftpweb pagesand emailultimately occur over sockets sockets are also sometimes called communications endpoints because they are the portals through which programs send and receive bytes during conversation although often used for network conversationssockets may also be used as communication mechanism between programs running on the same computertaking the form of general inter-process communication (ipcmechanism we saw this socket usage mode briefly in unlike some ipc devicessockets are bidirectional data streamsprograms may both send and receive data through them to programmerssockets take the form of handful of calls available in library these socket calls know how to send bytes between machinesusing lower-level operations such as the tcp network transmission control protocol at the bottomtcp knows how to transfer bytesbut it doesn' care what those bytes mean for the purposes of this textwe will generally ignore how bytes sent to sockets are physically transferred to understand sockets fullythoughwe need to know bit about how computers are named machine identifiers suppose for just moment that you wish to have telephone conversation with someone halfway across the world in the real worldyou would probably need either that person' telephone number or directory that you could use to look up the number from her name ( telephone bookthe same is true on the internetbefore script can have conversation with another computer somewhere in cyberspaceit must first know that other computer' number or name luckilythe internet defines standard ways to name both remote machine and service provided by that machine within scriptthe computer program to be contacted through socket is identified by supplying pair of values--the machine name and specific port number on that machinemachine names machine name may take the form of either string of numbers separated by dotscalled an ip address ( )or more legible form known as domain name ( starship python netdomain names are automatically mapped into their dotted numeric address equivalent when usedby something called plumbing the internet
5,350
local telephone directory assistance service as special casethe machine name localhostand its equivalent ip address always mean the same local machinethis allows us to refer to servers running locally on the same computer as its clients port numbers port number is an agreed-upon numeric identifier for given conversation because computers on the net support variety of servicesport numbers are used to name particular conversation on given machine for two machines to talk over the netboth must associate sockets with the same machine name and port number when initiating network connections as we'll seeinternet protocols such as email and the web have standard reserved port numbers for their connectionsso clients can request service regardless of the machine providing it port number for exampleusually provides web pages on any web server machine the combination of machine name and port number uniquely identifies every dialog on the net for instancean isp' computer may provide many kinds of services for customers--web pagestelnetftp transfersemailand so on each service on the machine is assigned unique port number to which requests may be sent to get web pages from web serverprograms need to specify both the web server' internet protocol (ipor domain name and the port number on which the server listens for web page requests if this sounds bit strangeit may help to think of it in old-fashioned terms to have telephone conversation with someone within companyfor exampleyou usually need to dial both the company' phone number and the extension of the person you want to reach if you don' know the company' numberyou can probably find it by looking up the company' name in phone book it' almost the same on the net--machine names identify collection of services (like company)port numbers identify an individual service within particular machine (like an extension)and domain names are mapped to ip numbers by domain name servers (like phone bookwhen programs use sockets to communicate in specialized ways with another machine (or with other processes on the same machine)they need to avoid using port number reserved by standard protocol--numbers in the range of to --but we first need to discuss protocols to understand why the protocol layer although sockets form the backbone of the internetmuch of the activity that happens on the net is programmed with protocols,which are higher-level message models that some books also use the term protocol to refer to lower-level transport schemes such as tcp in this bookwe use protocol to refer to higher-level structures built on top of socketssee networking text if you are curious about what happens at lower levels network scripting
5,351
to talk over sockets they generally standardize both message formats and socket port numbersmessage formats provide structure for the bytes exchanged over sockets during conversations port numbers are reserved numeric identifiers for the underlying sockets over which messages are exchanged raw sockets are still commonly used in many systemsbut it is perhaps more common (and generally easierto communicate with one of the standard higher-level internet protocols as we'll seepython provides support for standard protocolswhich automates most of the socket and message formatting details port number rules technically speakingsocket port numbers can be any -bit integer value between and , howeverto make it easier for programs to locate the standard protocolsport numbers in the range of to are reserved and preassigned to the standard higher-level protocols table - lists the ports reserved for many of the standard protocolseach gets one or more preassigned numbers from the reserved range table - port numbers reserved for common protocols protocol common function port number python module http web pages http clienthttp server nntp usenet news nntplib ftp data default file transfers ftplib ftp control file transfers ftplib smtp sending email smtplib pop fetching email poplib imap fetching email imaplib finger informational / ssh command lines /athird party telnet command lines telnetlib clients and servers to socket programmersthe standard protocols mean that port numbers to are off-limits to scriptsunless they really mean to use one of the higher-level protocols this is both by standard and by common sense telnet programfor instancecan start dialog with any telnet-capable machine by connecting to its port without preassigned port numberseach server might install telnet on different port similarlywebsites listen for page requests from browsers on port by standardif they did notplumbing the internet
5,352
surfing the net by defining standard port numbers for servicesthe net naturally gives rise to clientserver architecture on one side of conversationmachines that support standard protocols perpetually run set of programs that listen for connection requests on the reserved ports on the other end of dialogother machines contact those programs to use the services they export we usually call the perpetually running listener program server and the connecting program client let' use the familiar web browsing model as an example as shown in table - the http protocol used by the web allows clients and servers to talk over sockets on port server machine that hosts websites usually runs web server program that constantly listens for incoming connection requestson socket bound to port oftenthe server itself does nothing but watch for requests on its port perpetuallyhandling requests is delegated to spawned processes or threads clients programs that wish to talk to this server specify the server machine' name and port to initiate connection for web serverstypical clients are web browsers like firefoxinternet exploreror chromebut any script can open client-side connection on port to fetch web pages from the server the server' machine name can also be simply "localhostif it' the same as the client' in generalmany clients may connect to server over socketswhether it implements standard protocol or something more specific to given application and in some applicationsthe notion of client and server is blurred--programs can also pass bytes between each other more as peers than as master and subordinate an agent in peerto-peer file transfer systemfor instancemay at various times be both client and server for parts of files transferred for the purposes of this bookthoughwe usually call programs that listen on sockets serversand those that connect clients we also sometimes call the machines that these programs run on server and client ( computer on which web server program runs may be called web server machinetoo)but this has more to do with the physical than the functional protocol structures functionallyprotocols may accomplish familiar tasklike reading email or posting usenet newsgroup messagebut they ultimately consist of message bytes sent over sockets the structure of those message bytes varies from protocol to protocolis hidden by the python libraryand is mostly beyond the scope of this bookbut few general words may help demystify the protocol layer network scripting
5,353
specify the sequence of control messages exchanged during conversations by defining regular patterns of communicationprotocols make communication more robust they can also minimize deadlock conditions--machines waiting for messages that never arrive for examplethe ftp protocol prevents deadlock by conversing over two socketsone for control messages only and one to transfer file data an ftp server listens for control messages ( "send me file"on one portand transfers file data over another ftp clients open socket connections to the server machine' control portsend requestsand send or receive file data over socket connected to data port on the server machine ftp also defines standard message structures passed between client and server the control message used to request filefor instancemust follow standard format python' internet library modules if all of this sounds horribly complexcheer uppython' standard protocol modules handle all the details for examplethe python library' ftplib module manages all the socket and message-level handshaking implied by the ftp protocol scripts that import ftplib have access to much higher-level interface for ftping files and can be largely ignorant of both the underlying ftp protocol and the sockets over which it runs +in facteach supported protocol is represented in python' standard library by either module package of the same name as the protocol or by module file with name of the form xxxlib pywhere xxx is replaced by the protocol' name the last column in table - gives the module name for some standard protocol modules for instanceftp is supported by the module file ftplib py and http by package http moreoverwithin the protocol modulesthe top-level interface object is often the name of the protocol sofor instanceto start an ftp session in python scriptyou run import ftplib and pass appropriate parameters in call to ftplib ftpfor telnetcreate telnetlib telnet instance in addition to the protocol implementation modules in table - python' standard library also contains modules for fetching replies from web servers for web page request (urllib request)parsing and handling data once it has been transferred over sockets or protocols (html parserthe email and xml packages)and more table - lists some of the more commonly used modules in this category +since python is an open source systemyou can read the source code of the ftplib module if you are curious about how the underlying protocol actually works see the ftplib py file in the standard source library directory in your machine its code is complex (since it must format messages and manage two sockets)but with the other standard internet protocol modulesit is good example of low-level socket programming plumbing the internet
5,354
python modules utility socketssl network and ipc communications support (tcp/ipudpetc )plus ssl secure sockets wrapper cgi server-side cgi script supportparse input streamescape html textand so on urllib request fetch web pages from their addresses (urlsurllib parse parse url string into componentsescape url text http clientftplibnntplib http (web)ftp (file transfer)and nntp (newsclient protocol modules http cookieshttp cookiejar http cookies support (data stored on clients by website requestserverand client-side supportpoplibimaplibsmtplib popimap (mail fetch)and smtp (mail sendprotocol modules telnetlib telnet protocol module html parserxml parse web page contents (html and xml documentsxdrlibsocket encode binary data portably for transmission structpickle encode python objects as packed binary data or serialized byte strings for transmission email parse and compose email messages with headersattachmentsand encodings mailbox process on disk mailboxes and their messages mimetypes guess file content types from names and extensions from types uubinhexbase binasciiquopriemail encode and decode binary (or otherdata transmitted as text (automatic in email packagesocketserver framework for general net servers http server basic http server implementationwith request handlers for simple and cgi-aware servers we will meet many of the modules in this table in the next few of this bookbut not all of them moreoverthere are additional internet modules in python not shown here the modules demonstrated in this book will be representativebut as alwaysbe sure to see python' standard library reference manual for more complete and up-to-date lists and details more on protocol standards if you want the full story on protocols and portsat this writing you can find comprehensive list of all ports reserved for protocols or registered as used by various common systems by searching the web pages maintained by the internet engineering task force (ietfand the internet assigned numbers authority (ianathe ietf is the organization responsible for maintaining web protocols and standards the iana is the central coordinator for the assignment of unique parameter values for internet protocols another standards bodythe (for www)also maintains relevant documents see these web pages for more details network scripting
5,355
it' not impossible that more recent repositories for standard protocol specifications will arise during this book' shelf lifebut the ietf website will likely be the main authority for some time to come if you do lookthoughbe warned that the details arewelldetailed because python' protocol modules hide most of the socket and messaging complexity documented in the protocol standardsyou usually don' need to memorize these documents to get web work done with python socket programming now that we've seen how sockets figure into the internet picturelet' move on to explore the tools that python provides for programming sockets with python scripts this section shows you how to use the python socket interface to perform low-level network communications in later we will instead use one of the higher-level protocol modules that hide underlying sockets python' socket interfaces can be used directlythoughto implement custom network dialogs and to access standard protocols manually as previewed in the basic socket interface in python is the standard library' socket module like the os posix modulepython' socket module is just thin wrapper (interface layerover the underlying library' socket calls like python filesit' also object-based--methods of socket object implemented by this module call out to the corresponding library' operations after data conversions for instancethe library' send and recv function calls become methods of socket objects in python python' socket module supports socket programming on any machine that supports bsd-style sockets--windowsmacslinuxunixand so on--and so provides portable socket interface in additionthis module supports all commonly used socket types--tcp/ipudpdatagramand unix domain--and can be used as both network interface api and general ipc mechanism between processes running on the same machine from functional perspectivesockets are programmer' device for transferring bytes between programspossibly running on different computers although sockets themselves transfer only byte stringswe can also transfer python objects through them by using python' pickle module because this module converts python objects such as listsdictionariesand class instances to and from byte stringsit provides the extra step needed to ship higher-level objects through sockets when required socket programming
5,356
data byte strings for transmissionbut is generally limited in scope to objects that map to types in the programming language the pickle module supports transmission of larger objectsuch as dictionaries and class instances for other tasksincluding most standard internet protocolssimpler formatted byte strings suffice we'll learn more about pickle later in this and book beyond basic data communication tasksthe socket module also includes variety of more advanced tools for instanceit has calls for the following and moreconverting bytes to standard network ordering (ntohlhtonlquerying machine name and address (gethostnamegethostbynamewrapping socket objects in file object interface (sockobj makefilemaking socket calls nonblocking (sockobj setblockingsetting socket timeouts (sockobj settimeoutprovided your python was compiled with secure sockets layer (sslsupportthe ssl standard library module also supports encrypted transfers with its ssl wrap_socket call this call wraps socket object in ssl logicwhich is used in turn by other standard library modules to support the https secure website protocol (http client and urllib request)secure email transfers (poplib and smtplib)and more we'll meet some of these other modules later in this part of the bookbut we won' study all of the socket module' advanced features in this textsee the python library manual for usage details omitted here socket basics although we won' get into advanced socket use in this basic socket transfers are remarkably easy to code in python to create connection between machinespython programs import the socket modulecreate socket objectand call the object' methods to establish connections and send and receive data sockets are inherently bidirectional in natureand socket object methods map directly to socket calls in the library for examplethe script in example - implements program that simply listens for connection on socket and echoes back over socket whatever it receives through that socketadding echo=string prefixes example - pp \internet\sockets\echo-server py ""server sideopen tcp/ip socket on portlisten for message from clientand send an echo replythis is simple one-shot listen/reply conversation per clientbut it goes into an infinite loop to listen for more clients as long as this server script runsthe client may run on remote machineor on same computer if it uses 'localhostfor server "" network scripting
5,357
myhost 'myport get socket constructor and constants 'all available interfaces on host listen on non-reserved port number sockobj socket(af_inetsock_streamsockobj bind((myhostmyport)sockobj listen( make tcp socket object bind it to server port number listenallow pending connects while trueconnectionaddress sockobj accept(print('server connected by'addresswhile truedata connection recv( if not databreak connection send( 'echo=>dataconnection close(listen until process killed wait for next client connect connection is new socket read next line on client socket send reply line to the client until eof when socket closed as mentioned earlierwe usually call programs like this that listen for incoming connections servers because they provide service that can be accessed at given machine and port on the internet programs that connect to such server to access its service are generally called clients example - shows simple client implemented in python example - pp \internet\sockets\echo-client py ""client sideuse sockets to send data to the serverand print server' reply to each message line'localhostmeans that the server is running on the same machine as the clientwhich lets us test client and server on one machineto test over the internetrun server on remote machineand set serverhost or argv[ to machine' domain name or ip addrpython sockets are portable bsd socket interfacewith object methods for the standard socket calls available in the system' library""import sys from socket import serverhost 'localhostserverport portable socket interface plus constants server nameor'starship python netnon-reserved port used by the server message [ 'hello network world'default text to send to server requires bytesb'or str,encode(if len(sys argv serverhost sys argv[ server from cmd line arg if len(sys argv text from cmd line args message ( encode(for in sys argv[ :]sockobj socket(af_inetsock_streamsockobj connect((serverhostserverport)make tcp/ip socket object connect to server machine port for line in messagesockobj send(linedata sockobj recv( print('client received:'datasend line to server over socket receive line from serverup to bytes are quotedwas ` `repr(xsockobj close(close socket to send eof to server socket programming
5,358
before we see these programs in actionlet' take minute to explain how this client and server do their stuff both are fairly simple examples of socket scriptsbut they illustrate the common call patterns of most socket-based programs in factthis is boilerplate codemost connected socket programs generally make the same socket calls that our two scripts doso let' step through the important points of these scripts line by line programs such as example - that provide services for other programs with sockets generally start out by following this sequence of callssockobj socket(af_inetsock_streamuses the python socket module to create tcp socket object the names af_inet and sock_stream are preassigned variables defined by and imported from the socket moduleusing them in combination means "create tcp/ip socket,the standard communication device for the internet more specificallyaf_inet means the ip address protocoland sock_stream means the tcp transfer protocol the af_inet/sock_stream combination is the default because it is so commonbut it' typical to make this explicit if you use other names in this callyou can instead create things like udp connectionless sockets (use sock_dgram secondand unix domain sockets on the local machine (use af_unix first)but we won' do so in this book see the python library manual for details on these and other socket module options using other socket types is mostly matter of using different forms of boilerplate code sockobj bind((myhostmyport)associates the socket object with an address--for ip addresseswe pass server machine name and port number on that machine this is where the server identifies the machine and port associated with the socket in server programsthe hostname is typically an empty string ("")which means the machine that the script runs on (formallyall available local and remote interfaces on the machine)and the port is number outside the range to (which is reserved for standard protocolsdescribed earliernote that each unique socket dialog you support must have its own port numberif you try to open socket on port already in usepython will raise an exception also notice the nested parentheses in this call--for the af_inet address protocol socket herewe pass the host/port socket address to bind as two-item tuple object (pass string for af_unixtechnicallybind takes tuple of values appropriate for the type of socket created sockobj listen( starts listening for incoming client connections and allows for backlog of up to five pending requests the value passed sets the number of incoming client requests queued by the operating system before new requests are denied (which happens only if server isn' fast enough to process requests before the queues fill upa network scripting
5,359
least at this pointthe server is ready to accept connection requests from client programs running on remote machines (or the same machineand falls into an infinite loop-while true (or the equivalent while for older pythons and ex- programmers)-waiting for them to arriveconnectionaddress sockobj accept(waits for the next client connection request to occurwhen it doesthe accept call returns brand-new socket object over which data can be transferred from and to the connected client connections are accepted on sockobjbut communication with client happens on connectionthe new socket this call actually returns two-item tuple--address is the connecting client' internet address we can call accept more than one timeto service multiple client connectionsthat' why each call returns newdistinct socket for talking to particular client once we have client connectionwe fall into another loop to receive data from the client in blocks of up to , bytes at timeand echo each block back to the clientdata connection recv( reads at most , more bytes of the next message sent from client ( coming across the network or ipc connection)and returns it to the script as byte string we get back an empty byte string when the client has finished--end-of-file is triggered when the client closes its end of the socket connection send( 'echo=>datasends the latest byte string data block back to the client programprepending the string 'echo=>to it first the client program can then recv what we send here-the next reply line technically this call sends as much data as possibleand returns the number of bytes actually sent to be fully robustsome programs may need to resend unsent portions or use connection sendall to force all bytes to be sent connection close(shuts down the connection with this particular client transferring byte strings and objects so far we've seen calls used to transfer data in serverbut what is it that is actually shipped through socketas we learned in sockets by themselves always deal in binary byte stringsnot text to your scriptsthis means you must send and will receive bytes stringsnot strthough you can convert to and from text as needed with bytes decode and str encode methods in our scriptswe use bbytes literals to satisfy socket data requirements in other contextstools such as the struct and pickle modules return the byte strings we need automaticallyso no extra steps are needed socket programming
5,360
send and receive nearly arbitrary python objects with the standard library pickle object serialization module its dumps and loads calls convert python objects to and from byte stringsready for direct socket transferimport pickle pickle dumps([ ]on sending end convert to byte strings '\ \ ] \ (kckde string passed to sendreturned by recv pickle loads( [ on receiving end convert back to object for simpler types that correspond to those in the languagethe struct module provides the byte-string conversion we need as wellimport struct struct pack('>ii' '\ \ \ \ \ \ dstruct unpack('>ii' ( convert simpler types for transmission when converted this waypython native objects become candidates for socket-based transfers see for more on struct we previewed pickle and object serialization in but we'll learn more about it and its few pickleability constraints when we explore data persistence in in fact there are variety of ways to extend the basic socket transfer model for instancemuch like os fdopen and open for the file descriptors we studied in the socket makefile method allows you to wrap sockets in text-mode file objects that handle text encodings for you automatically this call also allows you to specify nondefault unicode encodings and end-line behaviors in text mode with extra arguments in just like the open built-in function because its result mimics file interfacesthe socket makefile call additionally allows the pickle module' file-based calls to transfer objects over sockets implicitly we'll see more on socket file wrappers later in this for our simpler scripts herehardcoded byte strings and direct socket calls do the job after talking with given connected clientthe server in example - goes back to its infinite loop and waits for the next client connection request let' move on to see what happened on the other side of the fence client socket calls the actual socket-related calls in client programs like the one shown in example - are even simplerin facthalf of that script is preparation logic the main thing to keep in mind is that the client and server must specify the same port number when opening their sockets and the client must identify the machine on which the server is network scripting
5,361
conversationoutside the standard protocol range here are the client' socket callssockobj socket(af_inetsock_streamcreates python socket object in the client programjust like the server sockobj connect((serverhostserverport)opens connection to the machine and port on which the server program is listening for client connections this is where the client specifies the string name of the service to be contacted in the clientwe can either specify the name of the remote machine as domain name ( starship python netor numeric ip address we can also give the server name as localhost (or the equivalent ip address to specify that the server program is running on the same machine as the clientthat comes in handy for debugging servers without having to connect to the net and againthe client' port number must match the server' exactly note the nested parentheses again--just as in server bind callswe really pass the server' host/port address to connect in tuple object once the client establishes connection to the serverit falls into loopsending message one line at time and printing whatever the server sends back after each line is sentsockobj send(linetransfers the next byte-string message line to the server over the socket notice that the default list of lines contains bytes strings ( 'just as on the serverdata passed through the socket must be byte stringthough it can be the result of manual str encode encoding call or an object conversion with pickle or struct if desired when lines to be sent are given as command-line arguments insteadthey must be converted from str to bytesthe client arranges this by encoding in generator expression ( call map(str encodesys argv[ :]would have the same effectdata sockobj recv( reads the next reply line sent by the server program technicallythis reads up to , bytes of the next reply message and returns it as byte string sockobj close(closes the connection with the serversending it the end-of-file signal and that' it the server exchanges one or more lines of text with each client that connects the operating system takes care of locating remote machinesrouting bytes sent between programs and possibly across the internetand (with tcpmaking sure that our messages arrive intact that involves lot of processingtoo--our strings may ultimately travel around the worldcrossing phone wiressatellite linksand more along the way but we can be happily ignorant of what goes on beneath the socket call layer when programming in python socket programming
5,362
let' put this client and server to work there are two ways to run these scripts--on either the same machine or two different machines to run the client and the server on the same machinebring up two command-line consoles on your computerstart the server program in oneand run the client repeatedly in the other the server keeps running and responds to requests made each time you run the client script in the other window for instancehere is the text that shows up in the ms-dos console window where 've started the server scriptc:\pp \internet\socketspython echo-server py server connected by ( ' server connected by ( ' server connected by ( ' the output here gives the address (machine ip name and port numberof each connecting client like most serversthis one runs perpetuallylistening for client connection requests this server receives threebut have to show you the client window' text for you to understand what this meansc:\pp \internet\socketspython echo-client py client receivedb'echo=>hello network worldc:\pp \internet\socketspython echo-client py localhost spam spam spam client receivedb'echo=>spamclient receivedb'echo=>spamclient receivedb'echo=>spamc:\pp \internet\socketspython echo-client py localhost shrubbery client receivedb'echo=>shrubberyherei ran the client script three timeswhile the server script kept running in the other window each client connected to the serversent it message of one or more lines of textand read back the server' reply--an echo of each line of text sent from the client and each time client is runa new connection message shows up in the server' window (that' why we got threebecause the server' coded as an infinite loopyou may need to kill it with task manager on windows when you're done testingbecause ctrl- in the server' console window is ignoredother platforms may fare better it' important to notice that client and server are running on the same machine here ( windows pcthe server and client agree on the port numberbut they use the machine names "and localhostrespectivelyto refer to the computer on which they are running in factthere is no internet connection to speak of this is just ipcof the sort we saw in sockets also work well as cross-program communications tools on single machine network scripting
5,363
to make these scripts talk over the internet rather than on single machine and sample the broader scope of socketswe have to do some extra work to run the server on different computer firstupload the server' source file to remote machine where you have an account and python here' how do it with ftp to site that hosts domain name of my ownlearning-python commost informational lines in the following have been removedyour server name and upload interface details will varyand there are other ways to copy files to computer ( ftp client guisemailweb page post formsand so on--see "tips on using remote serverson page for hints on accessing remote servers) :\pp \internet\socketsftp learning-python com connected to learning-python com user (learning-python com:(none))xxxxxxxx passwordyyyyyyyy ftpmkdir scripts ftpcd scripts ftpput echo-server py ftpquit once you have the server program loaded on the other computeryou need to run it there connect to that computer and start the server program usually telnet or ssh into my server machine and start the server program as perpetually running process from the command line the syntax in unix/linux shells can be used to run the server script in the backgroundwe could also make the server directly executable with #line and chmod command (see for detailshere is the text that shows up in window on my pc that is running ssh session with the free putty clientconnected to the linux server where my account is hosted (againless few deleted informational lines)login asxxxxxxxx xxxxxxxx@learning-python com' passwordyyyyyyyy last loginfri apr : : from ]cd scripts ]python echo-server py [ now that the server is listening for connections on the netrun the client on your local computer multiple times again this timethe client runs on different machine than the serverso we pass in the server' domain or ip name as client command-line argument the server still uses machine name of "because it always listens on whatever machine it runs on here is what shows up in the remote learning-python com server' ssh window on my pc]server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' socket programming
5,364
"connected bymessage appears in the server ssh window each time the client script is run in the client windowc:\pp \internet\socketspython echo-client py learning-python com client receivedb'echo=>hello network worldc:\pp \internet\socketspython echo-client py learning-python com ni ni ni client receivedb'echo=>niclient receivedb'echo=>niclient receivedb'echo=>nic:\pp \internet\socketspython echo-client py learning-python com shrubbery client receivedb'echo=>shrubberythe ping command can be used to get an ip address for machine' domain nameeither machine name form can be used to connect in the clientc:\pp \internet\socketsping learning-python com pinging learning-python com with bytes of datareply from bytes= time= ms ttl= ctrl- :\pp \internet\socketspython echo-client py brave sir robin client receivedb'echo=>braveclient receivedb'echo=>sirclient receivedb'echo=>robinthis output is perhaps bit understated-- lot is happening under the hood the clientrunning on my windows laptopconnects with and talks to the server program running on linux machine perhaps thousands of miles away it all happens about as fast as when client and server both run on the laptopand it uses the same library callsonly the server name passed to clients differs though simplethis illustrates one of the major advantages of using sockets for crossprogram communicationthey naturally support running the conversing programs on different machineswith little or no change to the scripts themselves in the processsockets make it easy to decouple and distribute parts of system over network when needed socket pragmatics before we move onthere are three practical usage details you should know firstyou can run the client and server like this on any two internet-aware machines where python is installed of courseto run the client and server on different computersyou need both live internet connection and access to another machine on which to run the server this need not be an expensive propositionthoughwhen sockets are openedpython is happy to initiate and use whatever connectivity you havebe it dedicated linewireless routercable modemor dial-up account moreoverif you don' have server network scripting
5,365
and server examples on the same machinelocalhostas shown earlierall you need then is computer that allows socketsand most do secondthe socket module generally raises exceptions if you ask for something invalid for instancetrying to connect to nonexistent server (or unreachable serversif you have no internet linkfailsc:\pp \internet\socketspython echo-client py www nonesuch com hello traceback (most recent call last)file "echo-client py"line in sockobj connect((serverhostserverport)connect to server machine socket error[errno connection attempt failed because the connected party did not properly respond after period of timeor established connection failed because connected host has failed to respond finallyalso be sure to kill the server process before restarting it againor else the port number will still be in useand you'll get another exceptionon my remote server machine]ps - pid tty pts/ pts/ pts/ stat ss rtime command : python echo-server py : -bash : ps - ]python echo-server py traceback (most recent call last)file "echo-server py"line in sockobj bind((myhostmyport)bind it to server port number socket error[errno only one usage of each socket address (protocolnetwork address/portis normally permitted series of ctrl-cs will kill the server on linux (be sure to type fg to bring it to the foreground first if started with an &)]fg python echo-server py traceback (most recent call last)file "echo-server py"line in connectionaddress sockobj accept(wait for next client connect keyboardinterrupt as mentioned earliera ctrl- kill key combination won' kill the server on my windows machinehowever to kill the perpetually running server process running locally on windowsyou may need to start task manager ( using ctrl-alt-delete key combination)and then end the python task by selecting it in the process listbox that appears closing the window in which the server is running will also suffice on windowsbut you'll lose that window' command history you can also usually kill server on linux with kill - pid shell command if it is running in another window or in the backgroundbut ctrl- requires less typing socket programming
5,366
some of this examples run server code on remote computer though you can also run the examples locally on localhostremote execution better captures the flexibility and power of sockets to run remotelyyou'll need access to an internet accessible computer with pythonwhere you can upload and run scripts you'll also need to be able to access the remote server from your pc to help with this last stephere are few hints for readers new to using remote servers to transfer scripts to remote machinethe ftp command is standard on windows machines and most others on windowssimply type it in console window to connect to an ftp server or start your favorite ftp client gui programon linuxtype the ftp command in an xterm window you'll need to supply your account name and password to connect to nonanonymous ftp site for anonymous ftpuse "anonymousfor the username and your email address for the password to run scripts remotely from command linetelnet is standard command on some unix-like machinestoo on windowsit' often run as client gui for some server machinesyou'll need to use ssh secure shell rather than telnet to access shell prompt there are variety of ssh utilities available on the webincluding puttyused for this book python itself comes with telnetlib telnet moduleand web search will reveals current ssh options for python scriptsincluding ssh pyparamikotwistedpexpectand even subprocess popen spawning clients in parallel so farwe've run server locally and remotelyand run individual clients manuallyone after another realistic servers are generally intended to handle many clientsof courseand possibly at the same time to see how our echo server handles the loadlet' fire up eight copies of the client script in parallel using the script in example - see the end of for details on the launchmodes module used here to spawn clients and alternatives such as the multiprocessing and subprocess modules example - pp \internet\sockets\testecho py import sys from pp launchmodes import quietportablelauncher numclients def start(cmdline)quietportablelauncher(cmdlinecmdline)(start('echo-server py'spawn server locally if not yet started args join(sys argv[ :]for in range(numclients)start('echo-client py %sargspass server name if running remotely network scripting spawn clients to test the server
5,367
local machinepass real machine name to talk to server running remotely three console windows come into play in this scheme--the clienta local serverand remote server on windowsthe clientsoutput is discarded when spawned from this scriptbut it would be similar to what we've already seen here' the client window interaction-- clients are spawned locally to talk to both local and remote serverc:\pp \internet\socketsset pythonpath= :\dev\examples :\pp \internet\socketspython testecho py :\pp \internet\socketspython testecho py learning-python com if the spawned clients connect to server run locally (the first run of the script on the client)connection messages show up in the server' window on the local machinec:\pp \internet\socketspython echo-server py server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' if the server is running remotelythe client connection messages instead appear in the window displaying the ssh (or otherconnection to the remote computerherelearning-python com]python echo-server py server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' previewdenied client connections the net effect is that our echo server converses with multiple clientswhether running locally or remotely keep in mindhoweverthat this works for our simple scripts only because the server doesn' take long time to respond to each client' requests--it can get back to the top of the server script' outer while loop in time to process the next incoming client if it could notwe would probably need to change the server to handle each client in parallelor some might be denied connection technicallyclient connections would fail after clients are already waiting for the server' attentionas specified in the server' listen call to prove this to yourselfadd time sleep call somewhere inside the echo server' main loop in example - after socket programming
5,368
while trueconnectionaddress sockobj accept(while truedata connection recv( time sleep( listen until process killed wait for next client connect read next line on client socket take time to process request if you then run this server and the testecho clients scriptyou'll notice that not all clients wind up receiving connectionbecause the server is too busy to empty its pending-connections queue in time only clients are served when run this on windows--one accepted initiallyand in the pending-requests listen queue the other two clients are denied connections and fail the following shows the server and client messages produced when the server is stalled this wayincluding the error messages that the two denied clients receive to see the clientsmessages on windowsyou can change testecho to use the startargs launcher with / switch at the front of the command line to route messages to the persistent console window (see file testecho-messages py in the examples package) :\pp \dev\examples\pp \internet\socketsecho-server-sleep py server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' server connected by ( ' :\pp \dev\examples\pp \internet\socketstestecho-messages py / echo-client py / echo-client py / echo-client py / echo-client py / echo-client py / echo-client py / echo-client py / echo-client py client receivedb'echo=>hello network worldtraceback (most recent call last)file " :\pp \internet\sockets\echo-client py"line in sockobj connect((serverhostserverport)connect to server machine socket error[errno no connection could be made because the target machine actively refused it traceback (most recent call last)file " :\pp \internet\sockets\echo-client py"line in sockobj connect((serverhostserverport)connect to server machine socket error[errno no connection could be made because the target machine actively refused it network scripting
5,369
client receivedb'echo=>hello network worldclient receivedb'echo=>hello network worldclient receivedb'echo=>hello network worldclient receivedb'echo=>hello network worldas you can seewith such sleepy server clients are spawnedbut only receive serviceand fail with exceptions unless clients require very little of the server' attentionto handle multiple requests overlapping in time we need to somehow service clients in parallel we'll see how servers can handle multiple clients more robustly in momentfirstthoughlet' experiment with some special ports talking to reserved ports it' also important to know that this client and server engage in proprietary sort of discussionand so use the port number outside the range reserved for standard protocols ( to there' nothing preventing client from opening socket on one of these special portshowever for instancethe following client-side code connects to programs listening on the standard emailftpand http web server ports on three different server machinesc:\pp \internet\socketspython from socket import sock socket(af_inetsock_streamsock connect(('pop secureserver net' )talk to pop email server print(sock recv( ) '+ok \ \nsock close(sock socket(af_inetsock_streamsock connect(('learning-python com' )talk to ftp server print(sock recv( ) ' welcome to pure-ftpd [privsep[tls\ \ -yousock close(sock socket(af_inetsock_streamsock connect(('www python net' )talk to python' http server sock send( 'get /\ \ 'fetch root page reply sock recv( '<!doctype html public "-// //dtd xhtml strict//en"\ \ sock recv( 'www org/tr/xhtml /dtd/xhtml -strict dtd">\ \ <html xmlns="if we know how to interpret the output returned by these portsserverswe could use raw sockets like this to fetch emailtransfer filesand grab web pages and invoke serverside scripts fortunatelythoughwe don' have to worry about all the underlying details--python' poplibftpliband http client and urllib request modules provide higher-level interfaces for talking to servers on these ports other python protocol socket programming
5,370
meet some of these client-side protocol modules in the next ss binding reserved port servers speaking of reserved portsit' all right to open client-side connections on reserved ports as in the prior sectionbut you can' install your own server-side scripts for these ports unless you have special permission on the server use to host learningpython comfor instancethe web server port is off limits (presumablyunless shell out for virtual or dedicated hosting account)]python from socket import sock socket(af_inetsock_streamsock bind(('' )traceback (most recent call last)file ""line in file ""line in bind socket error( 'permission denied'try to bind web port on general server learning-python com is shared machine even if run by user with the required permissionyou'll get the different exception we saw earlier if the port is already being used by real web server on computers being used as general serversthese ports really are reserved this is one reason we'll run web server of our own locally for testing when we start writing server-side scripts later in this book--the above code works on windows pcwhich allows us to experiment with websites locallyon self-contained machinec:\pp \internet\socketspython from socket import sock socket(af_inetsock_streamsock bind(('' )can bind port on windows allows running server on localhost we'll learn more about installing web servers later in for the purposes of this we need to get realistic about how our socket servers handle their clients handling multiple clients the echo client and server programs shown previously serve to illustrate socket fundamentals but the server model used suffers from fairly major flaw as described earlierif multiple clients try to connect to the serverand it takes long time to process given client' requestthe server will fail more accuratelyif the cost of handling given ss you might be interested to know that the last part of this exampletalking to port is exactly what your web browser does as you surf the webfollowed links direct it to download web pages over this port in factthis lowly port is the primary basis of the web in we will meet an entire application environment based upon sending formatted data over port --cgi server-side scripting at the bottomthoughthe web is just bytes over socketswith user interface the wizard behind the curtain is not as impressive as he may seem network scripting
5,371
timely mannerit won' be able to keep up with all the requestsand some clients will eventually be denied connections in real-world client/server programsit' far more typical to code server so as to avoid blocking new requests while handling current client' request perhaps the easiest way to do so is to service each client' request in parallel--in new processin new threador by manually switching (multiplexingbetween clients in an event loop this isn' socket issue per seand we already learned how to start processes and threads in but since these schemes are so typical of socket server programminglet' explore all three ways to handle client requests in parallel here forking servers the script in example - works like the original echo serverbut instead forks new process to handle each new client connection because the handleclient function runs in new processthe dispatcher function can immediately resume its main loop in order to detect and service new incoming request example - pp \internet\sockets\fork-server py ""server sideopen socket on portlisten for message from clientand send an echo replyforks process to handle each client connectionchild processes share parent' socket descriptorsfork is less portable than threads--not yet on windowsunless cygwin or similar installed""import ostimesys from socket import myhost 'myport get socket constructor and constants server machine'means local host listen on non-reserved port number sockobj socket(af_inetsock_streamsockobj bind((myhostmyport)sockobj listen( make tcp socket object bind it to server port number allow pending connects def now()return time ctime(time time()current time on server activechildren [def reapchildren()while activechildrenpidstat os waitpid( os wnohangif not pidbreak activechildren remove(piddef handleclient(connection)time sleep( while truedata connection recv( if not databreak reap any dead child processes else may fill up system table don' hang if no child exited child processreplyexit simulate blocking activity readwrite client socket till eof when socket closed handling multiple clients
5,372
connection send(reply encode()connection close(os _exit( def dispatcher()listen until process killed while truewait for next connectionconnectionaddress sockobj accept(pass to process for service print('server connected by'addressend='print('at'now()reapchildren(clean up exited children now childpid os fork(copy this process if childpid = if in child processhandle handleclient(connectionelseelsego accept next connect activechildren append(childpidadd to active child pid list dispatcher(running the forking server parts of this script are bit trickyand most of its library calls work only on unix-like platforms cruciallyit runs on cygwin python on windowsbut not standard windows python before we get into too many forking detailsthoughlet' focus on how this server arranges to handle multiple client requests firstnotice that to simulate long-running operation ( database updatesother network traffic)this server adds five-second time sleep delay in its client handler functionhandleclient after the delaythe original echo reply action is performed that means that when we run server and clients this timeclients won' receive the echo reply until five seconds after they've sent their requests to the server to help keep track of requests and repliesthe server prints its system time each time client connect request is receivedand adds its system time to the reply clients print the reply time sent back from the servernot their own--clocks on the server and client may differ radicallyso to compare apples to applesall times are server times because of the simulated delayswe also must usually start each client in its own console window on windows (clients will hang in blocked state while waiting for their replybut the grander story here is that this script runs one main parent process on the server machinewhich does nothing but watch for connections (in dispatcher)plus one child process per active client connectionrunning in parallel with both the main parent process and the other client processes (in handleclientin principlethe server can handle any number of clients without bogging down to testlet' first start the server remotely in ssh or telnet windowand start three clients locally in three distinct console windows as we'll see in momentthis server can also be run under cygwin locally if you have cygwin but don' have remote server account like the one on learning-python com used here network scripting
5,373
]uname - - gnu/linux ]python fork-server py server connected by ( ' at sat apr : : server connected by ( ' at sat apr : : server connected by ( ' at sat apr : : [client window :\pp \internet\socketspython echo-client py learning-python com client receivedb"echo=> 'hello network worldat sat apr : : [client window :\pp \internet\socketspython echo-client py learning-python com bruce client receivedb"echo=> 'bruceat sat apr : : [client window :\socketspython echo-client py learning-python com the meaning of life client receivedb"echo=> 'theat sat apr : : client receivedb"echo=> 'meaningat sat apr : : client receivedb"echo=> 'ofat sat apr : : client receivedb"echo=> 'lifeat sat apr : : againall times here are on the server machine this may be little confusing because four windows are involved in plain englishthe test proceeds as follows the server starts running remotely all three clients are started and connect to the server few seconds apart on the serverthe client requests trigger three forked child processeswhich all immediately go to sleep for five seconds (to simulate being busy doing something useful each client waits until the server replieswhich happens five seconds after their initial requests in other wordsclients are serviced at the same time by forked processeswhile the main parent process continues listening for new client requests if clients were not handled in parallel like thisno client could connect until the currently connected client' fivesecond delay expired in more realistic applicationthat delay could be fatal if many clients were trying to connect at once--the server would be stuck in the action we're simulating with time sleepand not get back to the main loop to accept new client requests with process forks per requestclients can be serviced in parallel notice that we're using the same client script here (echo-client pyfrom example - )just different serverclients simply send and receive data to machine and port and don' care how their requests are handled on the server the result displayed shows byte string within byte stringbecause the client sends one to the server and the server sends one backbecause the server uses string formatting and manual handling multiple clients
5,374
string explicitly here other run modeslocal servers with cygwin and remote clients also note that the server is running remotely on linux machine in the preceding section as we learned in the fork call is not supported on windows in standard python at the time this book was written it does run on cygwin pythonthoughwhich allows us to start this server locally on localhoston the same machine as its clients[cygwin shell window[ :\pp \internet\socekts]python fork-server py server connected by ( ' at sat apr : : server connected by ( ' at sat apr : : [windows consolesame machinec:\pp \internet\socketspython echo-client py localhost bright side of life client receivedb"echo=> 'brightat sat apr : : client receivedb"echo=> 'sideat sat apr : : client receivedb"echo=> 'ofat sat apr : : client receivedb"echo=> 'lifeat sat apr : : [windows consolesame machinec:\pp \internet\socketspython echo-client py client receivedb"echo=> 'hello network worldat sat apr : : we can also run this test on the remote linux server entirelywith two ssh or telnet windows it works about the same as when clients are started locallyin dos console windowbut here "localactually means remote machine you're using locally just for funlet' also contact the remote server from locally running client to show how the server is also available to the internet at large--when servers are coded with sockets and forks this wayclients can connect from arbitrary machinesand can overlap arbitrarily in time[one ssh (or telnetwindow]python fork-server py server connected by ( ' at sat apr : : server connected by ( ' at sat apr : : server connected by ( ' at sat apr : : server connected by ( ' at sat apr : : [another ssh windowsame machine]python echo-client py client receivedb"echo=> 'hello network worldat sat apr : : ]python echo-client py localhost nininiclient receivedb"echo=> 'ninini!at sat apr : : ]python echo-client py localhost say no moreclient receivedb"echo=> 'sayat sat apr : : client receivedb"echo=> 'noat sat apr : : client receivedb"echo=> 'more!at sat apr : : [windows consolelocal machine network scripting
5,375
client receivedb"echo=> 'blue,at sat apr : : client receivedb"echo=> 'noat sat apr : : client receivedb"echo=> 'yellow!at sat apr : : now that we have handle on the basic modellet' move on to the tricky bits this server script is fairly straightforward as forking code goesbut few words about the library tools it employs are in order forked processes and sockets we met os fork in but recall that forked processes are essentially copy of the process that forks themand so they inherit file and socket descriptors from their parent process as resultthe new child process that runs the handleclient function has access to the connection socket created in the parent process reallythis is why the child process works at all--when conversing on the connected socketit' using the same socket that parent' accept call returns programs know they are in forked child process if the fork call returns otherwisethe original parent process gets back the new child' id exiting from children in earlier fork exampleschild processes usually call one of the exec variants to start new program in the child process hereinsteadthe child process simply calls function in the same program and exits with os _exit it' imperative to call os _exit here-if we did noteach child would live on after handleclient returnsand compete for accepting new client requests in factwithout the exit callwe' wind up with as many perpetual server processes as requests served--remove the exit call and do ps shell command after running few clientsand you'll see what mean with the callonly the single parent process listens for new requests os _exit is like sys exitbut it exits the calling process immediately without cleanup actions it' normally used only in child processesand sys exit is used everywhere else killing the zombiesdon' fear the reapernotehoweverthat it' not quite enough to make sure that child processes exit and die on systems like linuxthough not on cygwinparents must also be sure to issue wait system call to remove the entries for dead child processes from the system' process table if we don' do thisthe child processes will no longer runbut they will consume an entry in the system process table for long-running serversthese bogus entries may become problematic it' common to call such dead-but-listed child processes zombiesthey continue to use system resources even though they've already passed over to the great operating system beyond to clean up after child processes are gonethis server keeps listhandling multiple clients
5,376
incoming client request is receivedthe server runs its reapchildren to issue wait for any dead children by issuing the standard python os waitpid( ,os wnohangcall the os waitpid call attempts to wait for child process to exit and returns its process id and exit status with for its first argumentit waits for any child process with the wnohang parameter for its secondit does nothing if no child process has exited ( it does not block or pause the callerthe net effect is that this call simply asks the operating system for the process id of any child that has exited if any havethe process id returned is removed both from the system process table and from this script' activechildren list to see why all this complexity is neededcomment out the reapchildren call in this scriptrun it on platform where this is an issueand then run few clients on my linux servera ps - full process listing command shows that all the dead child processes stay in the system process table (show as )]ps - uid pid ppid stime tty : pts/ : pts/ : pts/ : pts/ : pts/ : pts/ : pts/ time cmd : : python fork-server py : : [python : : [python : : [python : : [python : : ps - : : -bash when the reapchildren command is reactivateddead child zombie entries are cleaned up each time the server gets new client connection requestby calling the python os waitpid function few zombies may accumulate if the server is heavily loadedbut they will remain only until the next client connection is received (you get only as many zombies as processes served in parallel since the last accept)]python fork-server py [ ]ps - uid pid ppid stime tty time cmd : pts/ : : python fork-server py : pts/ : : ps - : pts/ : : -bash ]server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : ]ps - uid pid ppid stime tty time cmd : pts/ : : python fork-server py : pts/ : : [python : pts/ : : [python : pts/ : : ps - : pts/ : : -bash ]server connected by ( ' at sun apr : : network scripting
5,377
uid pid ppid stime tty : pts/ : pts/ : pts/ : pts/ time cmd : : python fork-server py : : [python : : ps - : : -bash in factif you type fast enoughyou can actually see child process morph from real running program into zombie herefor examplea child spawned to handle new request changes to on exit its connection cleans up lingering zombiesand its own process entry will be removed completely when the next request is received]server connected by ( ' at sun apr : : ps - uid pid ppid stime tty time cmd : pts/ : : python fork-server py : pts/ : : python fork-server py : pts/ : : ps - : pts/ : : -bash ]ps - uid pid ppid stime tty time cmd : pts/ : : python fork-server py : pts/ : : [python : pts/ : : ps - : pts/ : : -bash preventing zombies with signal handlers on linux on some systemsit' also possible to clean up zombie child processes by resetting the signal handler for the sigchld signal delivered to parent process by the operating system when child process stops or exits if python script assigns the sig_ign (ignoreaction as the sigchld signal handlerzombies will be removed automatically and immediately by the operating system as child processes exitthe parent need not issue wait calls to clean up after them because of thatthis scheme is simpler alternative to manually reaping zombies on platforms where it is supported if you've already read you know that python' standard signal module lets scripts install handlers for signals--software-generated events by way of reviewhere is brief bit of background to show how this pans out for zombies the program in example - installs python-coded signal handler function to respond to whatever signal number you type on the command line example - pp \internet\sockets\signal-demo py ""demo python' signal modulepass signal number as command-line argand use "kill - pidshell command to send this process signalon my linux machinesigusr = sigusr = sigchld= and sigchld handler stays in effect even if not restoredall other handlers are restored by python after caughtbut sigchld behavior is left to the platform' implementationsignal works on windows toobut defines only few signal typessignals are not very portable in generalhandling multiple clients
5,378
import syssignaltime def now()return time asctime(def onsignal(signumstackframe)python signal handler print('got signal'signum'at'now()most handlers stay in effect if signum =signal sigchldbut sigchld handler is not print('sigchld caught'#signal signal(signal sigchldonsignalsignum int(sys argv[ ]signal signal(signumonsignalwhile truesignal pause(install signal handler sleep waiting for signals to run this scriptsimply put it in the background and send it signals by typing the kill -signal-number process-id shell command linethis is the shell' equivalent of python' os kill function available on unix-like platforms only process ids are listed in the pid column of ps command results here is this script in action catching signal numbers (reserved for general useand (the unavoidable terminate signal)]python signal-demo py [ ]ps - uid pid ppid stime tty : pts/ : pts/ : pts/ time cmd : : python signal-demo py : : ps - : : -bash ]kill - got signal at sun apr : : ]kill - got signal at sun apr : : ]kill - [ ]killed python signal-demo py and in the following the script catches signal which happens to be sigchld on my linux server signal numbers vary from machine to machineso you should normally use their namesnot their numbers sigchld behavior may vary per platform as well on my cygwin installfor examplesignal can have different meaningand signal is sigchld--on cygwinthe script works as shown on linux here for signal but generates an exception if it tries to install on handler for signal (and cygwin doesn' require reaping in any eventsee the signal module' library manual entry for more details]python signal-demo py [ ]ps - uid pid ppid stime tty network scripting time cmd
5,379
: pts/ : pts/ : pts/ : : python signal-demo py : : ps - : : -bash ]kill - got signal at sun apr : : sigchld caught ]kill - got signal at sun apr : : sigchld caught ]kill - [ ]killed python signal-demo py nowto apply all of this signal knowledge to killing zombiessimply set the sigchld signal handler to the sig_ign ignore handler actionon systems where this assignment is supportedchild processes will be cleaned up when they exit the forking server variant shown in example - uses this trick to manage its children example - pp \internet\sockets\fork-server-signal py ""same as fork-server pybut use the python signal module to avoid keeping child zombie processes after they terminateinstead of an explicit reaper loop before each new connectionsig_ign means ignoreand may not work with sig_chld child exit signal on all platformssee linux documentation for more about the restartability of socket accept call interrupted with signal""import ostimesyssignalsignal from socket import myhost 'myport get socket constructor and constants server machine'means local host listen on non-reserved port number sockobj socket(af_inetsock_streamsockobj bind((myhostmyport)sockobj listen( signal signal(signal sigchldsignal sig_ignmake tcp socket object bind it to server port number up to pending connects avoid child zombie processes def now()return time ctime(time time()time on server machine def handleclient(connection)child process repliesexits time sleep( simulate blocking activity while truereadwrite client socket data connection recv( if not databreak reply 'echo=>% at % (datanow()connection send(reply encode()connection close(os _exit( def dispatcher()while truelisten until process killed wait for next connectionhandling multiple clients
5,380
pass to process for service print('server connected by'addressend='print('at'now()childpid os fork(copy this process if childpid = if in child processhandle handleclient(connectionelsego accept next connect dispatcher(where applicablethis technique ismuch simplerwe don' need to manually track or reap child processes more accurateit leaves no zombies temporarily between client requests in factonly one line is dedicated to handling zombies herethe signal signal call near the topto set the handler unfortunatelythis version is also even less portable than using os fork in the first placebecause signals may work slightly differently from platform to platformeven among unix variants for instancesome unix platforms may not allow sig_ign to be used as the sigchld action at all on linux systemsthoughthis simpler forking server variant works like charm]python fork-server-signal py [ server connected by ( ' at sun apr : : ps - uid pid ppid stime tty : pts/ : pts/ : pts/ : pts/ time cmd : : python fork-server-signal py : : python fork-server-signal py : : ps - : : -bash ]ps - uid pid ppid stime tty : pts/ : pts/ : pts/ time cmd : : python fork-server-signal py : : ps - : : -bash notice how in this version the child process' entry goes away as soon as it exitseven before new client request is receivedno "defunctzombie ever appears more dramaticallyif we now start up the script we wrote earlier that spawns eight clients in parallel (testecho pyto talk to this server remotelyall appear on the server while runningbut are removed immediately as they exit[client windowc:\pp \internet\socketstestecho py learning-python com [server window]server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : network scripting
5,381
server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : ]ps - uid pid ppid stime tty : pts/ : pts/ : pts/ : pts/ : pts/ : pts/ : pts/ : pts/ : pts/ : pts/ : pts/ time cmd : : python fork-server-signal py : : python fork-server-signal py : : python fork-server-signal py : : python fork-server-signal py : : python fork-server-signal py : : python fork-server-signal py : : python fork-server-signal py : : python fork-server-signal py : : python fork-server-signal py : : ps - : : -bash ]ps - uid pid ppid stime tty : pts/ : pts/ : pts/ time cmd : : python fork-server-signal py : : ps - : : -bash and now that 've shown you how to use signal handling to reap children automatically on linuxi should underscore that this technique is not universally supported across all flavors of unix if you care about portabilitymanually reaping children as we did in example - may still be desirable why multiprocessing doesn' help with socket server portability in we learned about python' new multiprocessing module as we sawit provides way to start function calls in new processes that is more portable than the os fork call used in this section' server codeand it runs processes instead of threads to work around the thread gil in some scenarios in particularmultiprocessing works on standard windows python toounlike direct os fork calls experimented with server variant based upon this module to see if its portability might help for socket servers its full source code is in the examples package in file multi-server pybut here are its important bits that differrest unchanged from fork-server py from multiprocessing import process def handleclient(connection)print('child:'os getpid()time sleep( while truedata connection recv( rest unchanged child processreplyexit simulate blocking activity readwrite client socket till eof when socket closed def dispatcher()listen until process killed handling multiple clients
5,382
wait for next connectionconnectionaddress sockobj accept(pass to process for service print('server connected by'addressend='print('at'now()process(target=handleclientargs=(connection,)start(if __name__ ='__main__'print('parent:'os getpid()sockobj socket(af_inetsock_streamsockobj bind((myhostmyport)sockobj listen( dispatcher(make tcp socket object bind it to server port number allow pending connects this server variant is noticeably simpler too like the forking server it' derived fromthis server works fine under cygwin python on windows running as localhostand would probably work on other unix-like platforms as wellbecause multiprocessing forks process on such systemsand file and socket descriptors are inherited by child processes as usual hencethe child process uses the same connected socket as the parent here' the scene in cygwin server window and two windows client windows[server window[ :\pp \internet\sockets]python multi-server py parent server connected by ( ' at sat apr : : child server connected by ( ' at sat apr : : child [two client windowsc:\pp \internet\socketspython echo-client py client receivedb"echo=> 'hello network worldat sat apr : : :\pp \internet\socketspython echo-client py localhost brave sir robin client receivedb"echo=> 'braveat sat apr : : client receivedb"echo=> 'sirat sat apr : : client receivedb"echo=> 'robinat sat apr : : howeverthis server does not work on standard windows python--the whole point of trying to use multiprocessing in this context--because open sockets are not correctly pickled when passed as arguments into the new process here' what occurs in the server windows on windows with python :\pp \internet\socketspython multi-server py parent server connected by ( ' at sat apr : : child process process- traceback (most recent call last)file " :\python \lib\multiprocessing\process py"line in _bootstrap self run(file " :\python \lib\multiprocessing\process py"line in run self _target(*self _args**self _kwargsfile " :\pp \internet\sockets\multi-server py"line in handleclient data connection recv( till eof when socket closed network scripting
5,383
socket recall from that on windows multiprocessing passes context to new python interpreter process by pickling itand that process arguments must all be pickleable for windows sockets in python don' trigger errors when pickled thanks to the class they are an instance ofbut they are not really pickled correctlyfrom pickle import from socket import socket( dumps(ss loads(xx '\ \ csocket\nsocket\nq\ )\ \ } \ ( \ \ \ \ _io_refsq\ \ \ \ \ \ _closedq\ \ \ \ as we saw in multiprocessing has other ipc tools such as its own pipes and queues that might be used instead of sockets to work around this issuebut clients would then have to use themtoo--the resulting server would not be as broadly accessible as one based upon general internet sockets even if multiprocessing did work on windowsthoughits need to start new python interpreter would likely make it much slower than the more traditional technique of spawning threads to talk to clients coincidentallythat brings us to our next topic threading servers the forking model just described works well on unix-like platforms in generalbut it suffers from some potentially significant limitationsperformance on some machinesstarting new process can be fairly expensive in terms of time and space resources portability forking processes is unix techniqueas we've learnedthe os fork call currently doesn' work on non-unix platforms such as windows under standard python as we've also learnedforks can be used in the cygwin version of python on windowsbut they may be inefficient and not exactly the same as unix forks and as we just discoveredmultiprocessing won' help on windowsbecause connected sockets are not pickleable across process boundaries complexity if you think that forking servers can be complicatedyou're not alone as we just sawforking also brings with it all the shenanigans of managing and reaping zombies--cleaning up after child processes that live shorter lives than their parents handling multiple clients
5,384
threads rather than processes threads run in parallel and share global ( module and interpretermemory because threads all run in the same process and memory spacethey automatically share sockets passed between themsimilar in spirit to the way that child processes inherit socket descriptors unlike processesthoughthreads are usually less expensive to startand work on both unix-like machines and windows under standard python today furthermoremany (though not allsee threads as simpler to program--child threads die silently on exitwithout leaving behind zombies to haunt the server to illustrateexample - is another mutation of the echo server that handles client requests in parallel by running them in threads rather than in processes example - pp \internet\sockets\thread-server py ""server sideopen socket on portlisten for message from clientand send an echo replyechoes lines until eof when client closes socketspawns thread to handle each client connectionthreads share global memory space with main threadthis is more portable than forkthreads work on standard windows systemsbut process forks do not""import time_thread as thread from socket import myhost 'myport or use threading thread(start(get socket constructor and constants server machine'means local host listen on non-reserved port number sockobj socket(af_inetsock_streamsockobj bind((myhostmyport)sockobj listen( make tcp socket object bind it to server port number allow up to pending connects def now()return time ctime(time time()current time on the server def handleclient(connection)in spawned threadreply time sleep( simulate blocking activity while truereadwrite client socket data connection recv( if not databreak reply 'echo=>% at % (datanow()connection send(reply encode()connection close(def dispatcher()listen until process killed while truewait for next connectionconnectionaddress sockobj accept(pass to thread for service print('server connected by'addressend='print('at'now()thread start_new_thread(handleclient(connection,)dispatcher( network scripting
5,385
thread running the handleclient function as resultthis server can process multiple clients at onceand the main dispatcher loop can get quickly back to the top to check for newly arrived requests the net effect is that new clients won' be denied service due to busy server functionallythis version is similar to the fork solution (clients are handled in parallel)but it will work on any machine that supports threadsincluding windows and linux let' test it on both firststart the server on linux machine and run clients on both linux and windows[window thread-based server processserver keeps accepting client connections while threads are servicing prior requests]python thread-server py server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : [window clientbut on same remote server machine]python echo-client py client receivedb"echo=> 'hello network worldat sun apr : : [windows - local clientspcc:\pp \internet\socketspython echo-client py learning-python com client receivedb"echo=> 'hello network worldat sun apr : : :\pp \internet\socketspython echo-client py learning-python com bruce client receivedb"echo=> 'bruceat sun apr : : :\socketspython echo-client py learning-python com the meaning of life client receivedb"echo=> 'theat sun apr : : client receivedb"echo=> 'meaningat sun apr : : client receivedb"echo=> 'ofat sun apr : : client receivedb"echo=> 'lifeat sun apr : : because this server uses threads rather than forked processeswe can run it portably on both linux and windows pc here it is at work againrunning on the same local windows pc as its clientsagainthe main point to notice is that new clients are accepted while prior clients are being processed in parallel with other clients and the main thread (in the five-second sleep delay)[window serveron local pcc:\pp \internet\socketspython thread-server py server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : [windows - clientson local pcc:\pp \internet\socketspython echo-client py client receivedb"echo=> 'hello network worldat sun apr : : :\pp \internet\socketspython echo-client py localhost brian handling multiple clients
5,386
:\pp \internet\socketspython echo-client py localhost bright side of life client receivedb"echo=> 'brightat sun apr : : client receivedb"echo=> 'sideat sun apr : : client receivedb"echo=> 'ofat sun apr : : client receivedb"echo=> 'lifeat sun apr : : remember that thread silently exits when the function it is running returnsunlike the process fork versionwe don' call anything like os _exit in the client handler function (and we shouldn' --it may kill all threads in the processincluding the main loop watching for new connections!because of thisthe thread version is not only more portablebut also simpler standard library server classes now that 've shown you how to write forking and threading servers to process clients without blocking incoming requestsi should also tell you that there are standard tools in the python standard library to make this process even easier in particularthe socketserver module defines classes that implement all flavors of forking and threading servers that you are likely to be interested in like the manually-coded servers we've just studiedthis module' primary classes implement servers which process clients in parallel ( asynchronouslyto avoid denying service to new requests during long-running transactions their net effect is to automate the top-levels of common server code to use this modulesimply create the desired kind of imported server objectpassing in handler object with callback method of your ownas demonstrated in the threaded tcp server of example - example - pp \internet\sockets\class-server py ""server sideopen socket on portlisten for message from clientand send an echo replythis version uses the standard library module socketserver to do its worksocketserver provides tcpserverthreadingtcpserverforkingtcpserverudp variants of theseand moreand routes each client connect request to new instance of passed-in request handler object' handle methodsocketserver also supports unix domain socketsbut only on unixensee the python library manual ""import socketservertime myhost 'myport def now()return time ctime(time time()get socket serverhandler objects server machine'means local host listen on non-reserved port number class myclienthandler(socketserver baserequesthandler)def handle(self)on each client connect print(self client_addressnow()show this client' address time sleep( simulate blocking activity while trueself request is client socket network scripting
5,387
readwrite client socket if not databreak reply 'echo=>% at % (datanow()self request send(reply encode()self request close(make threaded serverlisten/handle clients forever myaddr (myhostmyportserver socketserver threadingtcpserver(myaddrmyclienthandlerserver serve_forever(this server works the same as the threading server we wrote by hand in the previous sectionbut instead focuses on service implementation (the customized handle method)not on threading details it is run the same waytoo--here it is processing three clients started by handplus eight spawned by the testecho script shown we wrote in example - [window serverserverhost='localhostin echo-client pyc:\pp \internet\socketspython class-server py ( ' sun apr : : ( ' sun apr : : ( ' sun apr : : ( ' sun apr : : ( ' sun apr : : ( ' sun apr : : ( ' sun apr : : ( ' sun apr : : ( ' sun apr : : ( ' sun apr : : ( ' sun apr : : [windows - clientsame machinec:\pp \internet\socketspython echo-client py client receivedb"echo=> 'hello network worldat sun apr : : :\pp \internet\socketspython echo-client py localhost arthur client receivedb"echo=> 'arthurat sun apr : : :\pp \internet\socketspython echo-client py localhost brave sir robin client receivedb"echo=> 'braveat sun apr : : client receivedb"echo=> 'sirat sun apr : : client receivedb"echo=> 'robinat sun apr : : :\pp \internet\socketspython testecho py to build forking server insteadjust use the class name forkingtcpserver when creating the server object the socketserver module has more power than shown by this exampleit also supports nonparallel ( serial or synchronousserversudp and unix domain socketsand ctrl- server interrupts on windows see python' library manual for more details for more advanced server needspython also comes with standard library tools that use those shown hereand allow you to implement in just few lines of python code handling multiple clients
5,388
scripts we'll explore those larger server tools in multiplexing servers with select so far we've seen how to handle multiple clients at once with both forked processes and spawned threadsand we've looked at library class that encapsulates both schemes under both approachesall client handlers seem to run in parallel with one another and with the main dispatch loop that continues watching for new incoming requests because all of these tasks run in parallel ( at the same time)the server doesn' get blocked when accepting new requests or when processing long-running client handler technicallythoughthreads and processes don' really run in parallelunless you're lucky enough to have machine with many cpus insteadyour operating system performs juggling act--it divides the computer' processing power among all active tasks it runs part of onethen part of anotherand so on all the tasks appear to run in parallelbut only because the operating system switches focus between tasks so fast that you don' usually notice this process of switching between tasks is sometimes called time-slicing when done by an operating systemit is more generally known as multiplexing when we spawn threads and processeswe rely on the operating system to juggle the active tasks so that none are starved of computing resourcesespecially the main server dispatcher loop howeverthere' no reason that python script can' do so as well for instancea script might divide tasks into multiple steps--run step of one taskthen one of anotherand so onuntil all are completed the script need only know how to divide its attention among the multiple active tasks to multiplex on its own servers can apply this technique to yield yet another way to handle multiple clients at oncea way that requires neither threads nor forks by multiplexing client connections and the main dispatcher with the select system calla single event loop can process multiple clients and accept new ones in parallel (or at least close enough to avoid stallingsuch servers are sometimes called asynchronousbecause they service clients in spurtsas each becomes ready to communicate in asynchronous serversa single main loop run in single process and thread decides which clients should get bit of attention each time through client requests and the main dispatcher loop are each given small slice of the server' attention if they are ready to converse most of the magic behind this server structure is the operating system select callavailable in python' standard select module on all major platforms roughlyselect is asked to monitor list of input sourcesoutput sourcesand exceptional condition sources and tells us which sources are ready for processing it can be made to simply poll all the sources to see which are readywait for maximum time period for sources to become readyor wait indefinitely until one or more sources are ready for processing network scripting
5,389
to avoid blocking on calls to ones that are not that iswhen the sources passed to select are socketswe can be sure that socket calls like acceptrecvand send will not block (pausethe server when applied to objects returned by select because of thata single-loop server that uses select need not get stuck communicating with one client or waiting for new ones while other clients are starved for the server' attention because this type of server does not need to start threads or processesit can be efficient when transactions with clients are relatively short-lived howeverit also requires that these transactions be quickif they are notit still runs the risk of becoming bogged down waiting for dialog with particular client to endunless augmented with threads or forks for long-running transactions | select-based echo server let' see how all of this translates into code the script in example - implements another echo serverone that can handle multiple clients without ever starting new processes or threads example - pp \internet\sockets\select-server py ""serverhandle multiple clients in parallel with select use the select module to manually multiplex among set of socketsmain sockets which accept new client connectionsand input sockets connected to accepted clientsselect can take an optional th arg-- to polln to wait secondsor omitted to wait till any socket is ready for processing ""import systime from select import select from socket import socketaf_inetsock_stream def now()return time ctime(time time()myhost 'myport if len(sys argv= myhostmyport sys argv[ :numportsocks server machine'means local host listen on non-reserved port number allow host/port as cmdline args too number of ports for client connects make main sockets for accepting new client requests mainsocksreadsockswritesocks [][][for in range(numportsocks)portsock socket(af_inetsock_streammake tcp/ip socket object |confusinglyselect-based servers are often called asynchronousto describe their multiplexing of short-lived transactions reallythoughthe classic forking and threading servers we met earlier are asynchronoustooas they do not wait for completion of given client' request there is clearer distinction between serial and parallel servers--the former process one transaction at time and the latter do not--and "synchronousand "asynchronousare essentially synonyms for "serialand "parallel by this definitionforkingthreadingand select loops are three alternative ways to implement parallelasynchronous servers handling multiple clients
5,390
portsock listen( mainsocks append(portsockreadsocks append(portsockmyport + bind it to server port number listenallow pending connects add to main list to identify add to select inputs list bind on consecutive ports event looplisten and multiplex until server process killed print('select-server loop starting'while true#print(readsocksreadableswriteablesexceptions select(readsockswritesocks[]for sockobj in readablesif sockobj in mainsocksfor ready input sockets port socketaccept new client newsockaddress sockobj accept(accept should not block print('connect:'addressid(newsock)newsock is new socket readsocks append(newsockadd to select listwait elseclient socketread next line data sockobj recv( recv should not block print('\tgot'data'on'id(sockobj)if not dataif closed by the clients sockobj close(close here and remv from readsocks remove(sockobjdel list else reselected elsethis may blockshould really select for writes too reply 'echo=>% at % (datanow()sockobj send(reply encode()the bulk of this script is its while event loop at the end that calls select to find out which sockets are ready for processingthese include both main port sockets on which clients can connect and open client connections it then loops over all such ready socketsaccepting connections on main port sockets and reading and echoing input on any client sockets ready for input both the accept and recv calls in this code are guaranteed to not block the server process after select returnsas resultthis server can quickly get back to the top of the loop to process newly arrived client requests and already connected clientsinputs the net effect is that all new requests and clients are serviced in pseudoparallel fashion to make this process workthe server appends the connected socket for each client to the readables list passed to selectand simply waits for the socket to show up in the selected inputs list for illustration purposesthis server also listens for new clients on more than one port--on ports and in our examples because these main port sockets are also interrogated with selectconnection requests on either port can be accepted without blocking either already connected clients or new connection requests appearing on the other port the select call returns whatever sockets in readables are ready for processing--both main port sockets and sockets connected to clients currently being processed network scripting
5,391
let' run this script locally to see how it does its stuff (the client and server can also be run on different machinesas in prior socket examplesfirstwe'll assume we've already started this server script on the local machine in one windowand run few clients to talk to it the following listing gives the interaction in two such client console windows running on windows the first client simply runs the echo-client script twice to contact the serverand the second also kicks off the testecho script to spawn eight echo-client programs running in parallel as beforethe server simply echoes back whatever text that client sendsthough without sleep pause here (more on this in momentnotice how the second client window really runs script called echo-client- so as to connect to the second port socket in the serverit' the same as echo-clientwith different hardcoded port numberalasthe original script wasn' designed to input port number[client window :\pp \internet\socketspython echo-client py client receivedb"echo=> 'hello network worldat sun apr : : :\pp \internet\socketspython echo-client py client receivedb"echo=> 'hello network worldat sun apr : : [client window :\pp \internet\socketspython echo-client- py localhost sir galahad client receivedb"echo=> 'sirat sun apr : : client receivedb"echo=> 'galahadat sun apr : : :\pp \internet\socketspython testecho py the next listing is the sort of output that show up in the window where the server has been started the first three connections come from echo-client runsthe rest is the result of the eight programs spawned by testecho in the second client window we can run this server on windowstoobecause select is available on this platform correlate this output with the server' code to see how it runs notice that for testechonew client connections and client inputs are multiplexed together if you study the output closelyyou'll see that they overlap in timebecause all activity is dispatched by the single event loop in the server in factthe trace output on the server will probably look bit different nearly every time it runs clients and new connections are interleaved almost at random due to timing differences on the host machines this happens in the earlier forking and treading serverstoobut the operating system automatically switches between the execution paths of the dispatcher loop and client transactions also note that the server gets an empty string when the client has closed its socket we take care to close and delete these sockets at the server right awayor else they would be needlessly reselected again and againeach time through the main loop[server windowc:\pp \internet\socketspython select-server py handling multiple clients
5,392
ct-server py select-server loop starting connect( ' got 'hello network worldon got 'on connect( ' got 'siron got 'galahadon got 'on connect( ' got 'hello network worldon got 'on [testecho resultsconnect( ' got 'hello network worldon got 'on connect( ' got 'hello network worldon got 'on connect( ' got 'hello network worldon got 'on connect( ' got 'hello network worldon got 'on connect( ' got 'hello network worldon got 'on connect( ' connect( ' got 'hello network worldon got 'hello network worldon connect( ' got 'on got 'on got 'hello network worldon got 'on besides this more verbose outputthere' another subtle but crucial difference to notice-- time sleep call to simulate long-running task doesn' make sense in the server here because all clients are handled by the same single loopsleeping would pause everythingand defeat the whole point of multiplexing server againmanual multiplexing servers like this one work well when transactions are shortbut also generally require them to either be soor be handled specially before we move onhere are few additional notes and optionsselect call details formallyselect is called with three lists of selectable objects (input sourcesoutput sourcesand exceptional condition sources)plus an optional timeout the timeout argument may be real wait expiration value in seconds (use floating-point network scripting
5,393
return immediatelyor omitted to mean wait until at least one object is ready (as done in our server scriptthe call returns triple of ready objects--subsets of the first three arguments--any or all of which may be empty if the timeout expired before sources became ready select portability like threadingbut unlike forkingthis server works in standard windows pythontoo technicallythe select call works only for sockets on windowsbut also works for things like files and pipes on unix and macintosh for servers running over the internetof coursethe primary devices we are interested in are sockets nonblocking sockets select lets us be sure that socket calls like accept and recv won' block (pausethe callerbut it' also possible to make python sockets nonblocking in general call the setblocking method of socket objects to set the socket to blocking or nonblocking mode for examplegiven call like sock setblocking(flag)the socket sock is set to nonblocking mode if the flag is zero and to blocking mode otherwise all sockets start out in blocking mode initiallyso socket calls may always make the caller wait howeverwhen in nonblocking modea socket error exception is raised if recv socket call doesn' find any dataor if send call can' immediately transfer data script can catch this exception to determine whether the socket is ready for processing in blocking modethese calls always block until they can proceed of coursethere may be much more to processing client requests than data transfers (requests may also require long-running computations)so nonblocking sockets don' guarantee that servers won' stall in general they are simply another way to code multiplexing servers like selectthey are better suited when client requests can be serviced quickly the asyncore module framework if you're interested in using selectyou will probably also be interested in checking out the asyncore py module in the standard python library it implements classbased callback modelwhere input and output callbacks are dispatched to class methods by precoded select event loop as suchit allows servers to be constructed without threads or forksand it is select-based alternative to the sock etserver module' threading and forking module we met in the prior sections as for this type of server in generalasyncore is best when transactions are short-what it describes as " / boundinstead of "cpu boundprogramsthe latter of which still require threads or forks see the python library manual for details and usage example twisted for other server optionssee also the open source twisted system (matrix comtwisted is an asynchronous networking framework written in python that supports tcpudpmulticastssl/tlsserial communicationand more it handling multiple clients
5,394
commonly used network services such as web serveran irc chat servera mail servera relational database interfaceand an object broker although twisted supports processes and threads for longer-running actionsit also uses an asynchronousevent-driven model to handle clientswhich is similar to the event loop of gui libraries like tkinter it abstracts an event loopwhich multiplexes among open socket connectionsautomates many of the details inherent in an asynchronous serverand provides an event-driven framework for scripts to use to accomplish application tasks twisted' internal event engine is similar in spirit to our select-based server and the asyncore modulebut it is regarded as much more advanced twisted is third-party systemnot standard library toolsee its website and documentation for more details summarychoosing server scheme so when should you use select to build serverinstead of threads or forksneeds vary per applicationof coursebut as mentionedservers based on the select call generally perform very well when client transactions are relatively short and are not cpu-bound if they are not shortthreads or forks may be better way to split processing among multiple clients threads and forks are especially useful if clients require long-running processing above and beyond the socket calls used to pass data howevercombinations are possible too--nothing is stopping select-based polling loop from using threadstoo it' important to remember that schemes based on select (and nonblocking socketsare not completely immune to blocking in example - for instancethe send call that echoes text back to client might blocktooand hence stall the entire server we could work around that blocking potential by using select to make sure that the output operation is ready before we attempt it ( use the writesocks list and add another loop to send replies to ready output sockets)albeit at noticeable cost in program clarity in generalthoughif we cannot split up the processing of client' request in such way that it can be multiplexed with other requests and not block the server' main loopselect may not be the best way to construct server by itself while some network servers can satisfy this constraintmany cannot moreoverselect also seems more complex than spawning either processes or threadsbecause we need to manually transfer control among all tasks (for instancecompare the threaded and select versions of our echo servereven without write selectsas usualthoughthe degree of that complexity varies per application the asyncore standard library module mentioned earlier simplifies some of the tasks of implementing select-based event-loop socket serverand twisted offers additional hybrid solutions network scripting
5,395
so far in this we've focused on the role of sockets in the classic client/server networking model that' one of their primary rolesbut they have other common use cases as well in for instancewe saw sockets as basic ipc device between processes and threads on single machine and in ' exploration of linking non-gui scripts to guiswe wrote utility module (example - which connected caller' standard output stream to socketon which gui could listen for output to be displayed therei promised that we' flesh out that module with additional transfer modes once we had chance to explore sockets in more depth now that we havethis section takes brief detour from the world of remote network servers to tell the rest of this story although some programs can be written or rewritten to converse over sockets explicitlythis isn' always an optionit may be too expensive an effort for existing scriptsand might preclude desirable nonsocket usage modes for others in some casesit' better to allow script to use standard stream tools such as the print and input built-in functions and sys module file calls ( sys stdout write)and connect them to sockets only when needed because such stream tools are designed to operate on text-mode filesthoughprobably the biggest trick here is fooling them into operating on the inherently binary mode and very different method interface of sockets luckilysockets come with method that achieves all the forgery we need the socket object makefile method comes in handy anytime you wish to process socket with normal file object methods or need to pass socket to an existing interface or program that expects file the socket wrapper object returned allows your scripts to transfer data over the underlying socket with read and write callsrather than recv and send since input and print built-in functions use the former methods setthey will happily interact with sockets wrapped by this calltoo the makefile method also allows us to treat normally binary socket data as text instead of byte stringsand has additional arguments such as encoding that let us specify nondefault unicode encodings for the transferred text--much like the built-in open and os fdopen calls we met in do for file descriptors although text can always be encoded and decoded with manual calls after binary mode socket transfersmake file shifts the burden of text encodings from your code to the file wrapper object this equivalence to files comes in handy any time we want to use software that supports file interfaces for examplethe python pickle module' load and dump methods expect an object with file-like interface ( read and write methods)but they don' require physical file passing tcp/ip socket wrapped with the makefile call to the pickler allows us to ship serialized python objects over the internetwithout having to pickle to byte strings ourselves and call raw socket methods manually this is an alternative to using the pickle module' string-based calls (dumpsloadswith socket send and making sockets look like files and streams
5,396
transport mechanisms see for more details on object serialization interfaces more generallyany component that expects file-like method protocol will gladly accept socket wrapped with socket object makefile call such interfaces will also accept strings wrapped with the built-in io stringio classand any other sort of object that supports the same kinds of method calls as built-in file objects as always in pythonwe code to protocols--object interfaces--not to specific datatypes stream redirection utility to illustrate the makefile method' operationexample - implements variety of redirection schemeswhich redirect the caller' streams to socket that can be used by another process for communication the first of its functions connects outputand is what we used in the others connect inputand both input and output in three different modes naturallythe wrapper object returned by socket makefile can also be used with direct file interface read and write method calls and independently of standard streams this example uses those methodstooalbeit in most cases indirectly and implicitly through the print and input stream access built-insand reflects common use case for the tool example - pp \internet\sockets\socket_stream_redirect py ""##############################################################################tools for connecting standard streams of non-gui programs to sockets that gui (or otherprogram can use to interact with the non-gui program ##############################################################################""import sys from socket import port host 'localhostpass in different port if multiple dialogs on machine pass in different host to connect to remote listeners def initlistenersocket(port=port)""initialize connected socket for callers that listen in server mode ""sock socket(af_inetsock_streamsock bind((''port)listen on this port number sock listen( set pending queue length connaddr sock accept(wait for client to connect return conn return connected socket def redirectout(port=porthost=host)""connect caller' standard output stream to socket for gui to listen start caller after listener startedelse connect fails before accept network scripting
5,397
sock socket(af_inetsock_streamsock connect((hostport)file sock makefile(' 'sys stdout file return sock caller operates in client mode file interfacetextbuffered make prints go to sock send if caller needs to access it raw def redirectin(port=porthost=host)""connect caller' standard input stream to socket for gui to provide ""sock socket(af_inetsock_streamsock connect((hostport)file sock makefile(' 'file interface wrapper sys stdin file make input come from sock recv return sock return value can be ignored def redirectbothasclient(port=porthost=host)""connect caller' standard input and output stream to same socket in this modecaller is client to serversends msgreceives reply ""sock socket(af_inetsock_streamsock connect((hostport)or open in 'rwmode ofile sock makefile(' 'file interfacetextbuffered ifile sock makefile(' 'two file objects wrap same socket sys stdout ofile make prints go to sock send sys stdin ifile make input come from sock recv return sock def redirectbothasserver(port=porthost=host)""connect caller' standard input and output stream to same socket in this modecaller is server to clientreceives msgsend reply ""sock socket(af_inetsock_streamsock bind((hostport)caller is listener here sock listen( connaddr sock accept(ofile conn makefile(' 'file interface wrapper ifile conn makefile(' 'two file objects wrap same socket sys stdout ofile make prints go to sock send sys stdin ifile make input come from sock recv return conn to testthe script in example - defines five sets of client/server functions it runs the client' code in processbut deploys the python multiprocessing module we met in to portably spawn the server function' side of the dialog in separate process in the endthe client and server test functions run in different processesbut converse over socket that is connected to standard streams within the test script' process making sockets look like files and streams
5,398
""##############################################################################test the socket_stream_redirection py modes ##############################################################################""import sysosmultiprocessing from socket_stream_redirect import ##############################################################################redirected client output ##############################################################################def server ()mypid os getpid(conn initlistenersocket(file conn makefile(' 'for in range( )data file readline(rstrip(print('server % got [% ](mypiddata)def client ()mypid os getpid(redirectout(for in range( )print('client % % (mypidi)sys stdout flush(block till client connect read/recv client' prints block till data ready print normally to terminal print to socket else buffered till exits##############################################################################redirected client input ##############################################################################def server ()mypid os getpid(raw socket not buffered conn initlistenersocket(send to client' input for in range( )conn send(('server % % \ (mypidi)encode()def client ()mypid os getpid(redirectin(for in range( )data input(print('client % got [% ](mypiddata)input from socket print normally to terminal ##############################################################################redirect client input outputclient is socket client ##############################################################################def server ()mypid os getpid(conn initlistenersocket(file conn makefile(' 'for in range( ) network scripting wait for client connect recv print()send input(readline blocks till data
5,399
conn send(('server % got [% ]\ (mypiddata)encode()def client ()mypid os getpid(redirectbothasclient(for in range( )print('client % % (mypidi)print to socket data input(input from socketflushessys stderr write('client % got [% ]\ (mypiddata)not redirected ##############################################################################redirect client input outputclient is socket server ##############################################################################def server ()mypid os getpid(sock socket(af_inetsock_streamsock connect((hostport)file sock makefile(' 'for in range( )sock send(('server % % \ (mypidi)encode()data file readline(rstrip(print('server % got [% ](mypiddata)send to input(recv from print(result to terminal def client ()mypid os getpid(redirectbothasserver( ' actually the socket server in this mode for in range( )data input(input from socketflushesprint('client % got [% ](mypiddata)print to socket sys stdout flush(else last buffered till exit##############################################################################redirect client input outputclient is socket clientserver xfers first ##############################################################################def server ()mypid os getpid(test but server accepts conn initlistenersocket(wait for client connect file conn makefile(' 'send input()recv print(for in range( )conn send(('server % % \ (mypidi)encode()data file readline(rstrip(print('server % got [% ](mypiddata)def client ()mypid os getpid( redirectbothasclient( ' the socket client in this mode for in range( )data input(input from socketflushesprint('client % got [% ](mypiddata)print to socket sys stdout flush(else last buffered till exit##############################################################################making sockets look like files and streams