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 w... |
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 /gif... |
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 ed... |
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(lab... |
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 upd... |
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... |
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'comm... |
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 b... |
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 modesobjec... |
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 ... |
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 tk... |
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... |
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 ... |
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 !se... |
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 pr... |
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)trac... |
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... |
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 n... |
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 w... |
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 ci... |
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 an... |
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 ... |
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 a... |
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 launch... |
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 ... |
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\c... |
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#################################... |
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- o... |
5,328 | onupdate called next ##############################################################################clock composite object ##############################################################################checkspersec second change timer class clock(frame)def __init__(selfconfig=clockconfigparent=none)frame __init__(selfpar... |
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 ... |
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######################################################################... |
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 e... |
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 ... |
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... |
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 wit... |
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 s... |
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 ... |
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 lay... |
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 intr... |
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 ... |
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 ... |
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 the... |
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-re... |
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 pythonperl... |
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 inter... |
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... |
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... |
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 server... |
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 impleme... |
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 a... |
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 conversatio... |
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 commonl... |
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 c... |
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 s... |
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 ... |
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 socke... |
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... |
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 accep... |
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 so... |
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 nex... |
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 sen... |
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 conn... |
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 serve... |
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 d... |
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=>niclien... |
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:... |
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... |
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 interacti... |
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 con... |
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 serv... |
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... |
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 clie... |
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 p... |
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 \... |
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 pythonthoughwhi... |
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 employ... |
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 p... |
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 ... |
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(signumons... |
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 igno... |
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 mo... |
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... |
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( dispa... |
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 pick... |
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... |
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 ... |
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 re... |
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 ser... |
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 wit... |
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 wi... |
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... |
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 t... |
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 wor... |
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 forkin... |
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 librarie... |
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... |
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 obj... |
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 pro... |
5,398 | ""##############################################################################test the socket_stream_redirection py modes ##############################################################################""import sysosmultiprocessing from socket_stream_redirect import #####################################################... |
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 #################################################################... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.