from socket import port host 'localhostdef redirectout(port=porthost=host)""connect caller' standard output stream to socket for gui to listenstart caller after listener startedelse connect fails before accept ""sock socket(af_inetsock_streamsock connect((hostport)caller operates in client mode file sock makefile(' 'file interfacetextbufferred sys stdout file make prints go to sock send def redirectin(port=porthost=host)def redirectbothasclient(port=porthost=host)def redirectbothasserver(port=porthost=host)see see see nextexample - uses example - to redirect its prints to socket on which gui server program may listenthis requires just two lines of code at the top of the scriptand is done selectively based upon the value of command-line argument (without the argumentthe script runs in fully non-gui mode)example - pp \gui\tools\socket-nongui py non-gui sideconnect stream to socket and proceed normally import timesys if len(sys argv from socket_stream_redirect import redirectout(link to gui only if requested connect my sys stdout to socket gui must be started first as is non-gui code while trueprint(time asctime()sys stdout flush(time sleep( print data to stdoutsent to gui process via socket must flush to sendbufferedno unbuffered mode- irrelevant and finallythe gui part of this exchange is the program in example - this script implements gui to display the text printed by the non-gui programbut it knows nothing of that other program' logic for the displaythe gui program prints to the stream redirection object we met earlier in this (example - )because this program runs gui mainloop callthis all just works we're also running timer loop here to detect incoming data on the socket as it arrivesinstead of waiting for the non-gui program to run to completion because the socket is set to be nonblockinginput calls don' wait for data to appearand hencedo not block the gui more ways to add guis to non-gui code