id
int64
0
25.6k
text
stringlengths
0
4.59k
5,400
##############################################################################if __name__ ='__main__'server eval('serversys argv[ ]client eval('clientsys argv[ ]multiprocessing process(target=serverstart(client(#import timetime sleep( client in this process server in new process reset streams in client test effect of exit flush run the test script with client and server number on the command line to test the module' toolsmessages display process id numbersand those within square brackets reflect transfer across streams connected to sockets (twicewhen nested) :\pp \internet\socketstest-socket_stream_redirect py server got [client server got [client server got [client :\pp \internet\socketstest-socket_stream_redirect py client got [server client got [server client got [server :\pp \internet\socketstest-socket_stream_redirect py client got [server got [client ]client got [server got [client ]client got [server got [client ] :\pp \internet\socketstest-socket_stream_redirect py server got [client got [server ]server got [client got [server ]server got [client got [server ] :\pp \internet\socketstest-socket_stream_redirect py server got [client got [server ]server got [client got [server ]server got [client got [server ]if you correlate this script' output with its code to see how messages are passed between client and serveryou'll find that print and input calls in client functions are ultimately routed over sockets to another process to the client functionsthe socket linkage is largely invisible text-mode files and buffered output streams before we move onthere are two remarkably subtle aspects of the example' code worth highlightingbinary to text translations raw sockets transfer binary byte stringsbut by opening the wrapper files in text modetheir content is automatically translated to text strings on input and output text-mode file wrappers are required if accessed through standard stream tools network scripting
5,401
files require byte strings insteadwhen dealing with the raw socket directlythoughtext must still be manually encoded to byte stringsas shown in most of example - ' tests buffered streamsprogram outputand deadlock as we learned in and standard streams are normally bufferedand printed text may need to be flushed so that it appears on socket connected to process' output stream indeedsome of this example' tests require explicit or implicit flush calls to work properly at allotherwise their output is either incomplete or absent altogether until program exit in pathological casesthis can lead to deadlockwith process waiting for output from another that never appears in other configurationswe may also get socket errors in reader if writer exits too soonespecially in two-way dialogs for exampleif client and client did not flush periodically as they dothe only reason that they would work is because output streams are automatically flushed when their process exits without manual flushesclient transfers no data until process exit (at which point all its output is sent at once in single message)and client ' data is incomplete till exit (its last printed message is delayedeven more subtlyboth client and client rely on the fact that the input builtin first automatically flushes sys stdout internally for its prompt optionthereby sending data from preceding print calls without this implicit flush (or the addition of manual flushes)client would experience deadlock immediatelyas would client if its manual flush call was removed (even with input' flushremoving client ' manual flush causes its final print message to not be transferred until process exitclient has this same behavior as client because it simply swaps which process binds and accepts and which connects in the general caseif we wish to read program' output as it is producedinstead of all at once when it exits or as its buffers fillthe program must either call sys stdout flush periodicallyor be run with unbuffered streams by using python' - command-line argument of if applicable although we can open socket wrapper files in unbuffered mode with second makefile argument of zero (like normal open)this does not allow the wrapper to run in the text mode required for print and desired for input in factattempting to make socket wrapper file both text mode and unbuffered this way fails with an exceptionbecause python no longer supports unbuffered mode for text files (it is allowed for binary mode only todayin other wordsbecause print requires text modebuffered mode is also implied for output stream files moreoverattempting to open socket file wrapper in line-buffered mode appears to not be supported in python (more on this aheadwhile some buffering behavior may be library and platform dependentmanual flush calls or direct socket access might sometimes still be required note that sockets can also be made nonblocking with the setblocking( methodbut this making sockets look like files and streams
5,402
failure to send buffered output stream requirements to make some of this more concreteexample - illustrates how some of these complexities apply to redirected standard streamsby attempting to connect them to both text and binary mode files produced by open and accessing them with print and input built-ins much as redirected script might example - pp \internet\sockets\test-stream-modes py ""test effect of connecting standard streams to text and binary mode files same holds true for socket makefileprint requires text modebut text mode precludes unbuffered mode -use - or sys stdout flush(calls ""import sys def reader( )tmpsys stdin sys stdinf line input(print(linesys stdin tmp readeropen('test-stream-modes py'readeropen('test-stream-modes py''rb'worksinput(returns text worksbut input(returns bytes def writer( )tmpsys stdout sys stdoutf print( 'spam'sys stdout tmp writeropen('temp'' 'print(open('temp'read()worksprint(passes text str to write(writeropen('temp''wb'writeropen('temp'' ' fails on printbinary mode requires bytes fails on opentext must be unbuffered when runthe last two lines in this script both fail--the second to last fails because print passes text strings to binary-mode file (never allowed for files in general)and the last fails because we cannot open text-mode files in unbuffered mode in python (text mode implies unicode encodingshere are the errors we get when this script is runthe first run uses the script as shownand the second shows what happens if the second to last line is commented out ( edited the exception text slightly for presentation) :\pp \internet\socketstest-stream-modes py "" '"""\ spam network scripting
5,403
file " :\pp \internet\sockets\test-stream-modes py"line in writeropen('temp''wb'fails on printbinary mode file " :\pp \internet\sockets\test-stream-modes py"line in writer print( 'spam'typeerrormust be bytes or buffernot str :\pp \internet\socketstest-streams-binary py "" '"""\ spam traceback (most recent call last)file " :\pp \internet\sockets\test-stream-modes py"line in writeropen('temp'' ' fails on opentext must be valueerrorcan' have unbuffered text / the same rules apply to socket wrapper file objects created with socket' makefile method--they must be opened in text mode for print and should be opened in text mode for input if we wish to receive text stringsbut text mode prevents us from using fully unbuffered file mode altogetherfrom socket import socket(defaults to tcp/ip (af_inetsock_streams makefile(' ' this used to work in python traceback (most recent call last)file " :\python \lib\socket py"line in makefile valueerrorunbuffered streams must be binary line buffering text-mode socket wrappers also accept buffering-mode argument of to specify linebuffering instead of the default full bufferingfrom socket import socket( makefile(' ' same as buffering= but acts as fully bufferedthis appears to be no different than full bufferingand still requires the resulting file to be flushed manually to transfer lines as they are produced consider the simple socket server and client scripts in examples - and - the server simply reads three messages using the raw socket interface example - pp \internet\sockets\socket-unbuff-server py from socket import sock socket(sock bind(('' )sock listen( print('accepting 'connid sock accept(read three messages over raw socket blocks till client connect for in range( )print('receiving 'making sockets look like files and streams
5,404
print(msgblocks till data received gets all print lines at once unless flushed the client in example - sends three messagesthe first two over socket wrapper fileand the last using the raw socketthe manual flush calls in this are commented out but retained so you can experiment with turning them onand sleep calls make the server wait for data example - pp \internet\sockets\socket-unbuff-client py import time send three msgs over wrapped and raw socket from socket import sock socket(default=af_inetsock_stream (tcp/ipsock connect(('localhost' )file sock makefile(' 'buffering= default=full buff =error not linebuffprint('sending data 'file write('spam\ 'time sleep( #file flush(print('sending data 'print('eggs'file=filetime sleep( #file flush(print('sending data 'sock send( 'ham\ 'time sleep( must follow with flush(to truly send now uncomment flush lines to see the difference adding more file prints does not flush buffer either output appears at server recv only upon flush or exit low-level byte string interface sends immediately received first if don' flush other tworun the server in one window first and the client in another (or run the server first in the background in unix-like platformsthe output in the server window follows-the messages sent with the socket wrapper are deferred until program exitbut the raw socket call transfers data immediatelyc:\pp \internet\socketssocket-unbuff-server py accepting receiving 'ham\nreceiving 'spam\ \neggs\ \nreceiving 'the client window simply displays "sendinglines seconds apartits third message appears at the server in secondsbut the first and second messages it sends using the wrapper file are deferred until exit (for secondsbecause the socket wrapper is still fully buffered if the manual flush calls in the client are uncommentedeach of the three sent messages is delivered in serial seconds apart (the third appears immediately after the second) network scripting
5,405
accepting receiving 'spam\ \nreceiving 'eggs\ \nreceiving 'ham\nin other wordseven when line buffering is requestedsocket wrapper file writes (and by associationprintsare buffered until the program exitsmanual flushes are requestedor the buffer becomes full solutions the short story here is thisto avoid delayed outputs or deadlockscripts that might send data to waiting programs by printing to wrapped sockets (or for that matterby using print or sys stdout write in generalshould do one of the followingcall sys stdout flush periodically to flush their printed output so it becomes available as producedas shown in example - be run with the - python command-line flagif possibleto force the output stream to be unbuffered this works for unmodified programs spawned by pipe tools such as os popen it will not help with the use case herethoughbecause we manually reset the stream files to buffered text socket wrappers after process starts to prove thisuncomment example - ' manual flush calls and the sleep call at its endand run with -uthe first test' output is still delayed for seconds use threads to read from sockets to avoid blockingespecially if the receiving program is gui and it cannot depend upon the client to flush see for pointers this doesn' really fix the problem--the spawned reader thread may be blocked or deadlockedtoo--but at least the gui remains active during waits implement their own custom socket wrapper objects which intercept text write callsencode to binaryand route to socket with send callssocket makefile is really just convenience tooland we can always code wrapper of our own for more specific roles for hintssee ' guioutput classthe stream redirection class in and the classes of the io standard library module (upon which python' input/output tools are basedand which you can mix in custom waysskip print altogether and communicate directly with the native interfaces of ipc devicessuch as socket objectsraw send and recv methods--these transfer data immediately and do not buffer data as file methods can we can either transfer simple byte strings this way or use the pickle module' dumps and loads tools to convert python objects to and from byte strings for such direct socket transfer (more on pickle in making sockets look like files and streams
5,406
the raw socket in support of such usage)but it isn' viable in all scenariosespecially for existing or multimode scripts in many casesit may be most straightforward to use manual flush calls in shell-oriented programs whose streams might be linked to other programs through sockets buffering in other contextscommand pipes revisited also keep in mind that buffered streams and deadlock are general issues that go beyond socket wrapper files we explored this topic in as quick reviewthe nonsocket example - does not fully buffer its output when it is connected to terminal (output is only line buffered when run from shell command prompt)but does if connected to something else (including socket or pipeexample - pp \internet\sockets\pipe-unbuff-writer py output line buffered (unbufferedif stdout is terminalbuffered by default for other devicesuse - or sys stdout flush(to avoid delayed output on pipe/socket import timesys for in range( )print(time asctime()sys stdout write('spam\ 'time sleep( print transfers per stream buffering ditto for direct stream file access unles sys stdout reset to other file although text-mode files are required for python ' print in generalthe - flag still works in to suppress full output stream buffering in example - using this flag makes the spawned script' printed output appear every secondsas it is produced not using this flag defers all output for secondsuntil the spawned script exitsunless the spawned script calls sys stdout flush on each iteration example - pp \internet\sockets\pipe-unbuff-reader py no output for seconds unless python - flag used or sys stdout flush(but writer' output appears here every seconds when either option is used import os for line in os popen('python - pipe-unbuff-writer py')print(lineend=''iterator reads lines blocks without -ufollowing is the reader script' outputunlike the socket examplesit spawns the writer automaticallyso we don' need separate windows to test recall from that os popen also accepts buffering argument much like socket makefilebut it does not apply to the spawned program' streamand so would not prevent output buffering in this case :\pp \internet\socketspipe-unbuff-reader py wed apr : : spam wed apr : : spam network scripting
5,407
spam wed apr : : spam wed apr : : spam the net effect is that - still works around the steam buffering issue for connected programs in xas long as you don' reset the streams to other objects in the spawned program as we did for socket redirection in example - for socket redirectionsmanual flush calls or replacement socket wrappers may be required sockets versus command pipes so why use sockets in this redirection role at allin shortfor server independence and networked use cases notice how for command pipes it' not clear who should be called "serverand "client,since neither script runs perpetually in factthis is one of the major downsides of using command pipes like this instead of sockets--because the programs require direct spawning relationshipcommand pipes do not support longerlived or remotely running servers the way that sockets do with socketswe can start client and server independentlyand the server may continue running perpetually to serve multiple clients (albeit with some changes to our utility module' listener initialization codemoreoverpassing in remote machine names to our socket redirection tools would allow client to connect to server running on completely different machine as we learned in named pipes (fifosaccessed with the open call support stronger independence of client and servertoobut unlike socketsthey are usually limited to the local machineand are not supported on all platforms experiment with this code on your own for more insight also try changing example - to run the client function in spawned process instead of or in addition to the serverwith and without flush calls and time sleep calls to defer exitsthe spawning structure might have some impact on the soundness of given socket dialog structure as wellwhich we'll finesse here in the interest of space despite the care that must be taken with text encodings and stream bufferingthe utility provided by example - is still arguably impressive--prints and input calls are routed over network or local-machine socket connections in largely automatic fashionand with minimal changes to the nonsocket code that uses the module in many casesthe technique can extend script' applicability in the next sectionwe'll use the makefile method again to wrap the socket in filelike objectso that it can be read by lines using normal text-file method calls and techniques this isn' strictly required in the example--we could read lines as byte strings with the socket recv calltoo in generalthoughthe makefile method comes in handy any time you wish to treat sockets as though they were simple files to see this at worklet' move on making sockets look like files and streams
5,408
it' time for something realistic let' conclude this by putting some of the socket ideas we've studied to work doing something bit more useful than echoing text back and forth example - implements both the server-side and the client-side logic needed to ship requested file from server to client machines over raw socket in effectthis script implements simple file download system one instance of the script is run on the machine where downloadable files live (the server)and another on the machines you wish to copy files to (the clientscommand-line arguments tell the script which flavor to run and optionally name the server machine and port number over which conversations are to occur server instance can respond to any number of client file requests at the port on which it listensbecause it serves each in thread example - pp \internet\sockets\getfile py ""############################################################################implement client and server-side logic to transfer an arbitrary file from server to client over socketuses simple control-info protocol rather than separate sockets for control and data (as in ftp)dispatches each client request to handler threadand loops to transfer the entire file by blockssee ftplib examples for higher-level transport scheme############################################################################""import sysostime_thread as thread from socket import blksz defaulthost 'localhostdefaultport helptext ""usage server=getfile py -mode server [-port nnn[-host hhh|localhostclient=getfile py [-mode client-file fff [-port nnn[-host hhh|localhost""def now()return time asctime(def parsecommandline()dict {args sys argv[ :while len(args> dict[args[ ]args[ args args[ :return dict put in dictionary for easy lookup skip program name at front of args exampledict['-mode''serverdef client(hostportfilename)sock socket(af_inetsock_streamsock connect((hostport) network scripting
5,409
send remote name with dirbytes dropdir os path split(filename)[ filename at end of dir path file open(dropdir'wb'create local file in cwd while truedata sock recv(blkszget up to at time if not databreak till closed on server side file write(datastore data in local file sock close(file close(print('client got'filename'at'now()def serverthread(clientsock)sockfile clientsock makefile(' 'wrap socket in dup file obj filename sockfile readline()[:- get filename up to end-line tryfile open(filename'rb'while truebytes file read(blkszread/send at time if not bytesbreak until file totally sent sent clientsock send(bytesassert sent =len(bytesexceptprint('error downloading file on server:'filenameclientsock close(def server(hostport)serversock socket(af_inetsock_streamlisten on tcp/ip socket serversock bind((hostport)serve clients in threads serversock listen( while trueclientsockclientaddr serversock accept(print('server connected by'clientaddr'at'now()thread start_new_thread(serverthread(clientsock,)def main(args)host args get('-host'defaulthostport int(args get('-port'defaultport)if args get('-mode'='server'if host ='localhost'host 'server(hostportelif args get('-file')client(hostportargs['-file']elseprint(helptextuse args or defaults is string in argv none if no -modeclient else fails remotely client mode needs -file if __name__ ='__main__'args parsecommandline(main(argsthis script isn' much different from the examples we saw earlier depending on the command-line arguments passedit invokes one of two functionsthe server function farms out each incoming client request to thread that transfers the requested file' bytes simple python file server
5,410
back in local file of the same name the most novel feature here is the protocol between client and serverthe client starts the conversation by shipping filename string up to the serverterminated with an endof-line characterand including the file' directory path in the server at the servera spawned thread extracts the requested file' name by reading the client socketand opens and transfers the requested file back to the clientone chunk of bytes at time running the file server and clients since the server uses threads to process clientswe can test both client and server on the same windows machine firstlet' start server instance and execute two client instances on the same machine while the server runs[server windowlocalhostc:\internet\socketspython getfile py -mode server server connected by ( ' at sun apr : : server connected by ( ' at sun apr : : [client windowlocalhostc:\internet\socketsdir / gif txt file not found :\internet\socketspython getfile py -file testdir\ora-lp gif client got testdir\ora-lp gif at sun apr : : :\internet\socketspython getfile py -file testdir\textfile txt -port client got testdir\textfile txt at sun apr : : clients run in the directory where you want the downloaded file to appear--the client instance code strips the server directory path when making the local file' name here the "downloadsimply copies the requested files up to the local parent directory (the dos fc command compares file contents) :\internet\socketsdir / gif txt ora-lp gif textfile txt :\internet\socketsfc / ora-lp gif testdir/ora-lp gif fcno differences encountered :\internet\socketsfc textfile txt testdir\textfile txt fcno differences encountered as usualwe can run server and clients on different machines as well for instancehere are the sort of commands we would use to launch the server remotely and fetch files from it locallyrun this on your own to see the client and server outputs[remote server window]python getfile py -mode server network scripting
5,411
:\internet\socketspython getfile py -mode client -host learning-python com -port -file python exe :\internet\socketspython getfile py -host learning-python com -file index html one subtle security point herethe server instance code is happy to send any serverside file whose pathname is sent from clientas long as the server is run with username that has read access to the requested file if you care about keeping some of your server-side files privateyou should add logic to suppress downloads of restricted files 'll leave this as suggested exercise herebut we will implement such filename checks in different getfile download tool later in this book adding user-interface frontend after all the gui commotion in the prior part of this bookyou might have noticed that we have been living in the realm of the command line for this entire -our socket clients and servers have been started from simple dos or linux shells nothing is stopping us from adding nice point-and-click user interface to some of these scriptsthoughgui and network scripting are not mutually exclusive techniques in factthey can be arguably "sexywhen used together well for instanceit would be easy to implement simple tkinter gui frontend to the clientside portion of the getfile script we just met such toolrun on the client machinemay simply pop up window with entry widgets for typing the desired filenameserverand so on once download parameters have been inputthe user interface could either import and call the getfile client function with appropriate option argumentsor build and run the implied getfile py command line using tools such as os systemos popensubprocessand so on using row frames and command lines to help make all of this more concretelet' very quickly explore few simple scripts that add tkinter frontend to the getfile client-side program all of these examples assume that you are running server instance of getfilethey merely add gui for the client side of the conversationto fetch file from the server the firstin example - uses form construction techniques we met in and to create dialog for inputting serverportand filename informationand simply constructs the #we'll see three more getfile programs before we leave internet scripting the next getfile py fetches file with the higher-level ftp interface instead of using raw socket callsand its http-getfile scripts fetch files over the http protocol later presents server-side getfile py cgi script that transfers file contents over the http port in response to request made in web browser client (files are sent as the output of cgi scriptall four of the download schemes presented in this text ultimately use socketsbut only the version here makes that use explicit simple python file server
5,412
part ii example - pp \internet\sockets\getfilegui- py ""launch getfile script client from simple tkinter guicould also use os fork+execos spawnv (see launcher)windowsreplace 'pythonwith 'startif not on path""import sysos from tkinter import from tkinter messagebox import showinfo def onreturnkey()cmdline ('python getfile py -mode client -file % -port % -host % (content['file'get()content['port'get()content['server'get())os system(cmdlineshowinfo('getfilegui- ''download complete'box tk(labels ['server''port''file'content {for label in labelsrow frame(boxrow pack(fill=xlabel(rowtext=labelwidth= pack(side=leftentry entry(rowentry pack(side=rightexpand=yesfill=xcontent[labelentry box title('getfilegui- 'box bind(''(lambda eventonreturnkey())mainloop(when runthis script creates the input form shown in figure - pressing the enter key (runs client-side instance of the getfile programwhen the generated getfile command line is finishedwe get the verification pop up displayed in figure - figure - getfilegui- in action network scripting
5,413
using grids and function calls the first user-interface script (example - uses the pack geometry manager and row frames with fixed-width labels to lay out the input form and runs the getfile client as standalone program as we learned in it' arguably just as easy to use the grid manager for layout and to import and call the client-side logic function instead of running program the script in example - shows how example - pp \internet\sockets\getfilegui- py ""samebut with grids and import+callnot packs and cmdlinedirect function calls are usually faster than running files""import getfile from tkinter import from tkinter messagebox import showinfo def onsubmit()getfile client(content['server'get()int(content['port'get())content['file'get()showinfo('getfilegui- ''download complete'box tk(labels ['server''port''file'rownum content {for label in labelslabel(boxtext=labelgrid(column= row=rownumentry entry(boxentry grid(column= row=rownumsticky= +wcontent[labelentry rownum + box columnconfigure( weight= make expandable simple python file server
5,414
button(text='submit'command=onsubmitgrid(row=rownumcolumn= columnspan= box title('getfilegui- 'box bind(''(lambda eventonsubmit())mainloop(this version makes similar window (figure - )but adds button at the bottom that does the same thing as an enter key press--it runs the getfile client procedure generally speakingimporting and calling functions (as done hereis faster than running command linesespecially if done more than once the getfile script is set up to work either way--as program or function library figure - getfilegui- in action using reusable form-layout class if you're like methoughwriting all the gui form layout code in those two scripts can seem bit tediouswhether you use packing or grids in factit became so tedious to me that decided to write general-purpose form-layout classshown in example - which handles most of the gui layout grunt work example - pp \internet\sockets\form py ""################################################################# reusable form classused by getfilegui (and others#################################################################""from tkinter import entrysize class formdef __init__(selflabelsparent=none)labelsize max(len(xfor in labels box frame(parentbox pack(expand=yesfill=xrows frame(boxbd= relief=grooverows pack(side=topexpand=yesfill=xself content { network scripting add non-modal form box pass field labels list box has rowsbuttons rows has row frames go=button or return key runs onsubmit method
5,415
row frame(rowsrow pack(fill=xlabel(rowtext=labelwidth=labelsizepack(side=leftentry entry(rowwidth=entrysizeentry pack(side=rightexpand=yesfill=xself content[labelentry button(boxtext='cancel'command=self oncancelpack(side=rightbutton(boxtext='submit'command=self onsubmitpack(side=rightbox master bind(''(lambda eventself onsubmit())def onsubmit(self)for key in self contentprint(key'\ =>\ 'self content[keyget()override this user inputs in self content[kdef oncancel(self)tk(quit(override if need default is exit class dynamicform(form)def __init__(selflabels=none)labels input('enter field names'split(form __init__(selflabelsdef onsubmit(self)print('field values 'form onsubmit(selfself oncancel(if __name__ ='__main__'import sys if len(sys argv= form(['name''age''job']elsedynamicform(mainloop(precoded fieldsstay after submit input fieldsgo away after submit compare the approach of this module with that of the form row builder function we wrote in ' example - while that example much reduced the amount of code requiredthe module here is noticeably more complete and automatic scheme--it builds the entire form given set of label namesand provides dictionary with every field' entry widget ready to be fetched running this module standalone triggers its self-test code at the bottom without arguments (and when double-clicked in windows file explorer)the self-test generates form with canned input fields captured in figure - and displays the fieldsvalues on enter key presses or submit button clicksc:\pp \internet\socketspython form py age = name =bob job =educatorentertainer with command-line argumentthe form class module' self-test code prompts for an arbitrary set of field names for the formfields can be constructed as dynamically as we simple python file server
5,416
like figure - shows the input form constructed in response to the following console interaction field names could be accepted on the command linetoobut the input built-in function works just as well for simple tests like this in this modethe gui goes away after the first submitbecause dynamicform onsubmit says soc:\pp \internet\socketspython form py enter field namesname email web locale field values locale =florida web =name =book email =pp @learning-python com figure - form testdynamic fields and last but not leastexample - shows the getfile user interface againthis time constructed with the reusable form layout class we need to fill in only the form labels list and provide an onsubmit callback method of our own all of the work needed to construct the form comes "for free,from the imported and widely reusable form superclass example - pp \internet\sockets\getfilegui py ""launch getfile client with reusable gui form classos chdir to target local dir if input (getfile stores in cwd) network scripting
5,417
""from form import form from tkinter import tkmainloop from tkinter messagebox import showinfo import getfileos class getfileform(form)def __init__(selfoneshot=false)root tk(root title('getfilegui'labels ['server name''port number''file name''local dir?'form __init__(selflabelsrootself oneshot oneshot def onsubmit(self)form onsubmit(selflocaldir self content['local dir?'get(portnumber self content['port number'get(servername self content['server name'get(filename self content['file name'get(if localdiros chdir(localdirportnumber int(portnumbergetfile client(servernameportnumberfilenameshowinfo('getfilegui''download complete'if self oneshottk(quit(else stay in last localdir if __name__ ='__main__'getfileform(mainloop(the form layout class imported here can be used by any program that needs to input form-like datawhen used in this scriptwe get user interface like that shown in figure - under windows (and similar on other versions and platformsfigure - getfilegui in action pressing this form' submit button or the enter key makes the getfilegui script call the imported getfile client client-side function as before this timethoughwe also simple python file server
5,418
there (getfile stores in the current working directorywhatever that may be when it is calledhere are the messages printed in the client' consolealong with check on the file transferthe server is still running above testdirbut the client stores the file elsewhere after it' fetched on the socketc:\internet\socketsgetfilegui py local dir= :\users\mark\temp file name =testdir\ora-lp gif server name =localhost port number = client got testdir\ora-lp gif at sun apr : : :\internet\socketsfc / :\users\mark\temp\ora-lp gif testdir\ora-lp gif fcno differences encountered as usualwe can use this interface to connect to servers running locally on the same machine (as done here)or remotely on different computer use different server name and file paths if you're running the server on remote machinethe magic of sockets make this all "just workin either local or remote modes one caveat worth pointing out herethe gui is essentially dead while the download is in progress (even screen redraws aren' handled--try covering and uncovering the window and you'll see what meanwe could make this better by running the download in threadbut since we'll see how to do that in the next when we explore the ftp protocolyou should consider this problem preview in closinga few final notesfirsti should point out that the scripts in this use tkinter techniques we've seen before and won' go into here in the interest of spacebe sure to see the gui in this book for implementation hints keep in mindtoothat these interfaces just add gui on top of the existing script to reuse its codeany command-line tool can be easily gui-ified in this way to make it more appealing and user friendly in for examplewe'll meet more useful client-side tkinter user interface for reading and sending email over sockets (pymailgui)which largely just adds gui to mail-processing tools generally speakingguis can often be added as almost an afterthought to program although the degree of user-interface and core logic separation varies per programkeeping the two distinct makes it easier to focus on each and finallynow that 've shown you how to build user interfaces on top of this getfilei should also say that they aren' really as useful as they might seem in particulargetfile clients can talk only to machines that are running getfile server in the next we'll discover another way to download files--ftp--which also runs on sockets but provides higher-level interface and is available as standard service on many machines on the net we don' generally need to start up custom server to transfer files over ftpthe way we do with getfile in factthe user-interface scripts in this could be easily changed to fetch the desired file with python' network scripting
5,419
just say"read on using serial ports socketsthe main subject of this are the programmer' interface to network connections in python scripts as we've seenthey let us write scripts that converse with computers arbitrarily located on networkand they form the backbone of the internet and the web if you're looking for lower-level way to communicate with devices in generalthoughyou may also be interested in the topic of python' serial port interfaces this isn' quite related to internet scriptingbut it' similar enough in spirit and is discussed often enough on the net to merit few words here in briefscripts can use serial port interfaces to engage in low-level communication with things like micemodemsand wide variety of serial devices and hardware serial port interfaces are also used to communicate with devices connected over infrared ports ( hand-held computers and remote modemssuch interfaces let scripts tap into raw data streams and implement device protocols of their own other python tools such as the ctypes and struct modules may provide additional tools for creating and extracting the packed binary data these ports transfer at this writingthere are variety of ways to send and receive data over serial ports in python scripts notable among these options is an open source extension package known as pyserialwhich allows python scripts to control serial ports on both windows and linuxas well as bsd unixjython (for java)and ironpython (for net and monounfortunatelythere is not enough space to cover this or any other serial port option in any sort of detail in this text as alwayssee your favorite web search engine for upto-date details on this front simple python file server
5,420
client-side scripting "socket to me!the preceding introduced internet fundamentals and explored sockets--the underlying communications mechanism over which bytes flow on the net in this we climb the encapsulation hierarchy one level and shift our focus to python tools that support the client-side interfaces of common internet protocols we talked about the internet' higher-level protocols in the abstract at the start of the preceding and you should probably review that material if you skipped over it the first time around in shortprotocols define the structure of the conversations that take place to accomplish most of the internet tasks we're all familiar with--reading emailtransferring files by ftpfetching web pagesand so on at the most basic levelall of these protocol dialogs happen over sockets using fixed and standard message structures and portsso in some sense this builds upon the last but as we'll seepython' protocol modules hide most of the underlying details--scripts generally need to deal only with simple objects and methodsand python automates the socket and messaging logic required by the protocol in this we'll concentrate on the ftp and email protocol modules in pythonand we'll peek at few others along the way (nntp newshttp web pagesand so onbecause it is so prevalentwe will especially focus on email in much of this as well as in the two to follow--we'll use tools and techniques introduced here in the larger pymailgui and pymailcgi client and server-side programs of and all of the tools employed in examples here are in the standard python library and come with the python system all of the examples here are also designed to run on the client side of network connection--these scripts connect to an already running server to request interaction and can be run from basic pc or other client device (they require only server to converse withand as usualall the code here is also designed to teach us something about python programming in general--we'll refactor ftp examples and package email code to show object-oriented programming (oopin action
5,421
on to explore scripts designed to be run on the server side instead python programs can also produce pages on web serverand there is support in the python world for implementing the server side of things like httpemailand ftp for nowlet' focus on the client ftptransferring files over the net as we saw in the preceding sockets see plenty of action on the net for instancethe last getfile example allowed us to transfer entire files between machines in practicethoughhigher-level protocols are behind much of what happens on the net protocols run on top of socketsbut they hide much of the complexity of the network scripting examples of the prior ftp--the file transfer protocol--is one of the more commonly used internet protocols it defines higher-level conversation model that is based on exchanging command strings and file contents over sockets by using ftpwe can accomplish the same task as the prior getfile scriptbut the interface is simplerstandard and more general--ftp lets us ask for files from any server machine that supports ftpwithout requiring that it run our custom getfile script ftp also supports more advanced operations such as uploading files to the servergetting remote directory listingsand more reallyftp runs on top of two socketsone for passing control commands between client and server (port )and another for transferring bytes by using two-socket modelftp avoids the possibility of deadlocks ( transfers on the data socket do not block dialogs on the control socketultimatelythoughpython' ftplib support module allows us to upload and download files at remote server machine by ftpwithout dealing in raw socket calls or ftp protocol details transferring files with ftplib because the python ftp interface is so easy to uselet' jump right into realistic example the script in example - automatically fetches ( "downloads"and there is also support in the python world for other technologies that some might classify as "client-side scripting,toosuch as jython/java appletsxml-rpc and soap web servicesand rich internet application tools like flexsilverlightpyjamasand ajax these were all introduced early in such tools are generally bound up with the notion of web-based interactions--they either extend the functionality of web browser running on client machineor simplify web server access in clients we'll study browser-based techniques in and hereclient-side scripting means the client side of common internet protocols such as ftp and emailindependent of the web or web browsers at the bottomweb browsers are really just desktop gui applications that make use of client-side protocolsincluding those we'll study heresuch as http and ftp see as well as the end of this for more on other client-side techniques client-side scripting
5,422
following downloads an image file (by defaultfrom remote ftp site opens the downloaded file with utility we wrote in example - in the download portion will run on any machine with python and an internet connectionthough you'll probably want to change the script' settings so it accesses server and file of your own the opening part works if your playfile py supports your platformsee for detailsand change as needed example - pp \internet\ftp\getone py #!/usr/local/bin/python "" python script to download and play media file by ftp uses ftplibthe ftp protocol handler which uses sockets ftp runs on sockets (one for dataone for control--on ports and and imposes message text formatsbut python' ftplib module hides most of this protocol' details change for your site/file ""import ossys from getpass import getpass from ftplib import ftp hidden password input socket-based ftp tools nonpassive false filename 'monkeys jpgdirname sitename 'ftp rmi netuserinfo ('lutz'getpass('pswd?')if len(sys argv filename sys argv[ force active mode ftp for serverfile to be downloaded remote directory to fetch from ftp site to contact use (for anonymous filename on command lineprint('connecting 'connection ftp(sitenameconnection login(*userinfoconnection cwd(dirnameif nonpassiveconnection set_pasv(falseconnect to ftp site default is anonymous login xfer at time to localfile force active ftp if server requires print('downloading 'localfile open(filename'wb'local file to store download connection retrbinary('retr filenamelocalfile write connection quit(localfile close(if input('open file?'in [' '' ']from pp system media playfile import playfile playfile(filenamemost of the ftp protocol details are encapsulated by the python ftplib module imported here this script uses some of the simplest interfaces in ftplib (we'll see others later in this but they are representative of the module in general transferring files with ftplib
5,423
ftplib ftp objectpassing in the string name (domain or ip styleof the machine you wish to connect toconnection ftp(sitenameconnect to ftp site assuming this call doesn' throw an exceptionthe resulting ftp object exports methods that correspond to the usual ftp operations in factpython scripts act much like typical ftp client programs--just replace commands you would normally type or select with method callsconnection login(*userinfoconnection cwd(dirnamedefault is anonymous login xfer at time to localfile once connectedwe log in and change to the remote directory from which we want to fetch file the login method allows us to pass in username and password as additional optional arguments to specify an account loginby defaultit performs anonymous ftp notice the use of the nonpassive flag in this scriptif nonpassiveconnection set_pasv(falseforce active ftp if server requires if this flag is set to truethe script will transfer the file in active ftp mode rather than the default passive mode we'll finesse the details of the difference here (it has to do with which end of the dialog chooses port numbers for the transfer)but if you have trouble doing transfers with any of the ftp scripts in this try using active mode as first step in python and laterpassive ftp mode is on by default nowopen local file to receive the file' contentand fetch the filelocalfile open(filename'wb'connection retrbinary('retr filenamelocalfile write once we're in the target remote directorywe simply call the retrbinary method to download the target server file in binary mode the retrbinary call will take while to completesince it must download big file it gets three argumentsan ftp command stringherethe string retr filenamewhich is the standard format for ftp retrievals function or method to which python passes each chunk of the downloaded file' bytesherethe write method of newly created and opened local file size for those chunks of byteshere , bytes are downloaded at timebut the default is reasonable if this argument is omitted because this script creates local file named localfile of the same name as the remote file being fetchedand passes its write method to the ftp retrieval methodthe remote file' contents will automatically appear in localclient-side file after the download is finished observe how this file is opened in wb binary output mode if this script is run on windows we want to avoid automatically expanding any \ bytes into \ \ byte sequences client-side scripting
5,424
opened in text mode we also want to avoid unicode issues in python --as we also saw in strings are encoded when written in text mode and this isn' appropriate for binary data such as images text-mode file would also not allow for the bytes strings passed to write by the ftp library' retrbinary in any eventso rb is effectively required here (more on output file modes laterfinallywe call the ftp quit method to break the connection with the server and manually close the local file to force it to be complete before it is further processed (it' not impossible that parts of the file are still held in buffers before the close call)connection quit(localfile close(and that' all there is to it--all the ftpsocketand networking details are hidden behind the ftplib interface module here is this script in action on windows machineafter the downloadthe image file pops up in windows picture viewer on my laptopas captured in figure - change the server and file assignments in this script to test on your ownand be sure your pythonpath environment variable includes the pp root' containeras we're importing across directories on the examples tree herec:\pp \internet\ftppython getone py pswdconnecting downloading open file? notice how the standard python getpass getpass is used to ask for an ftp password like the input built-in functionthis call prompts for and reads line of text from the console userunlike inputgetpass does not echo typed characters on the screen at all (see the moreplus stream redirection example of for related toolsthis is handy for protecting things like passwords from potentially prying eyes be carefulthough--after issuing warningthe idle gui echoes the password anyhowthe main thing to notice is that this otherwise typical python script fetches information from an arbitrarily remote ftp site and machine given an internet linkany information published by an ftp server on the net can be fetched by and incorporated into python scripts using interfaces such as these using urllib to download files in factftp is just one way to transfer information across the netand there are more general tools in the python library to accomplish the prior script' download perhaps the most straightforward is the python urllib request modulegiven an internet address string-- urlor universal resource locator--this module opens connection to the specified server and returns file-like object ready to be read with normal file object method calls ( readreadlinetransferring files with ftplib
5,425
we can use such higher-level interface to download anything with an address on the web--files published by ftp sites (using urls that start with ftp://)web pages and output of scripts that live on remote servers (using (using file:/urlsfor instancethe script in example - does the same as the one in example - but it uses the general urllib request module to fetch the source distribution fileinstead of the protocol-specific ftplib example - pp \internet\ftp\getone-urllib py #!/usr/local/bin/python "" python script to download file by ftp by its url stringuse higher-level urllib instead of ftplib to fetch fileurllib supports ftphttpclient-side httpsand local filesand handles proxiesredirectscookiesand moreurllib also allows downloads of html pagesimagestextetc see also python html/xml parsers for web pages fetched by urllib in ""import osgetpass from urllib request import urlopen client-side scripting socket-based web tools
5,426
password getpass getpass('pswd?'remote/local filename remoteaddr 'ftp://lutz:% @ftp rmi net/% ;type= (passwordfilenameprint('downloading'remoteaddrthis works toourllib request urlretrieve(remoteaddrfilenameremotefile urlopen(remoteaddrlocalfile open(filename'wb'localfile write(remotefile read()localfile close(remotefile close(returns input file-like object where to store data locally note how we use binary mode output file againurllib fetches return byte stringseven for http web pages don' sweat the details of the url string used hereit is fairly complexand we'll explain its structure and that of urls in general in we'll also use urllib again in this and later to fetch web pagesformat generated url stringsand get the output of remote scripts on the web technically speakingurllib request supports variety of internet protocols (httpftpand local filesunlike ftpliburllib request is generally used for reading remote objectsnot for writing or uploading them (though the http and ftp protocols support file uploads tooas with ftplibretrievals must generally be run in threads if blocking is concern but the basic interface shown in this script is straightforward the callremotefile urllib request urlopen(remoteaddrreturns input file-like object contacts the server named in the remoteaddr url string and returns file-like object connected to its download stream (herean ftp-based socketcalling this file' read method pulls down the file' contentswhich are written to local client-side file an even simpler interfaceurllib request urlretrieve(remoteaddrfilenamealso does the work of opening local file and writing the downloaded bytes into it-things we do manually in the script as coded this comes in handy if we want to download filebut it is less useful if we want to process its data immediately either waythe end result is the samethe desired server file shows up on the client machine the output is similar to the original versionbut we don' try to automatically open this time ( 've changed the password in the url here to protect the innocent) :\pp \internet\ftpgetone-urllib py pswddownloading ftp://lutz:xxxxxx@ftp rmi net/monkeys jpg;type= :\pp \internet\ftpfc monkeys jpg test\monkeys jpg fcno differences encountered :\pp \internet\ftpstart monkeys jpg transferring files with ftplib
5,427
and the server-side examples in as we'll see in in bigger termstools like the urllib request urlopen function allow scripts to both download remote files and invoke programs that are located on remote server machineand so serves as useful tool for testing and using web sites in python scripts in we'll also see that urllib parse includes tools for formatting (escapingurl strings for safe transmission ftp get and put utilities when present the ftplib interfaces in python classesstudents often ask why programmers need to supply the retr string in the retrieval method it' good question--the retr string is the name of the download command in the ftp protocolbut ftplib is supposed to encapsulate that protocol as we'll see in momentwe have to supply an arguably odd stor string for uploads as well it' boilerplate code that you accept on faith once you see itbut that begs the question you could propose patch to ftplibbut that' not really good answer for beginning python studentsand it may break existing code (the interface is as it is for reasonperhaps better answer is that python makes it easy to extend the standard library modules with higher-level interfaces of our own--with just few lines of reusable codewe can make the ftp interface look any way we want in python for instancewe couldonce and for allwrite utility modules that wrap the ftplib interfaces to hide the retr string if we place these utility modules in directory on pythonpaththey become just as accessible as ftplib itselfautomatically reusable in any python script we write in the future besides removing the retr string requirementa wrapper module could also make assumptions that simplify ftp operations into single function calls for instancegiven module that encapsulates and simplifies ftplibour python fetchand-play script could be further reduced to the script shown in example - --essentially just two function calls plus password promptbut with net effect exactly like example - when run example - pp \internet\ftp\getone-modular py #!/usr/local/bin/python "" python script to download and play media file by ftp uses getfile pya utility module which encapsulates ftp step ""import getfile from getpass import getpass filename 'monkeys jpgfetch with utility getfile getfile(file=filenamesite='ftp rmi net' client-side scripting
5,428
user=('lutz'getpass('pswd?'))refetch=truerest is the same if input('open file?'in [' '' ']from pp system media playfile import playfile playfile(filenamebesides having much smaller line countthe meat of this script has been split off into file for reuse elsewhere if you ever need to download file againsimply import an existing function instead of copying code with cut-and-paste editing changes in download operations would need to be made in only one filenot everywhere we've copied boilerplate codegetfile getfile could even be changed to use urllib rather than ftplib without affecting any of its clients it' good engineering download utility so just how would we go about writing such an ftp interface wrapper (he asksrhetorically)given the ftplib library modulewrapping downloads of particular file in particular directory is straightforward connected ftp objects support two download methodsretrbinary this method downloads the requested file in binary modesending its bytes in chunks to supplied functionwithout line-feed mapping typicallythe supplied function is write method of an open local file objectsuch that the bytes are placed in the local file on the client retrlines this method downloads the requested file in ascii text modesending each line of text to supplied function with all end-of-line characters stripped typicallythe supplied function adds \ newline (mapped appropriately for the client machine)and writes the line to local file we will meet the retrlines method in later examplethe getfile utility module in example - always transfers in binary mode with retrbinary that isfiles are downloaded exactly as they were on the serverbyte for bytewith the server' line-feed conventions in text files (you may need to convert line feeds after downloads if they look odd in your text editor--see your editor or system shell commands for pointersor write python script that opens and writes the text as neededexample - pp \internet\ftp\getfile py #!/usr/local/bin/python ""fetch an arbitrary file by ftp anonymous ftp unless you pass user=(namepswdtuple self-test ftps test file and site ""transferring files with ftplib
5,429
from os path import exists socket-based ftp tools file existence test def getfile(filesitediruser=()*verbose=truerefetch=false)""fetch file by ftp from site/directory anonymous or real loginbinary transfer ""if exists(fileand not refetchif verboseprint(file'already fetched'elseif verboseprint('downloading'filelocal open(file'wb'local file of same name tryremote ftp(siteconnect to ftp site remote login(*useranonymous=(or (namepswdremote cwd(dirremote retrbinary('retr filelocal write remote quit(finallylocal close(close file no matter what if verboseprint('download done 'caller handles exceptions if __name__ ='__main__'from getpass import getpass file 'monkeys jpgdir site 'ftp rmi netuser ('lutz'getpass('pswd?')getfile(filesitediruserthis module is mostly just repackaging of the ftp code we used to fetch the image file earlierto make it simpler and reusable because it is callable functionthe exported getfile getfile here tries to be as robust and generally useful as possiblebut even function this small implies some design decisions here are few usage notesftp mode the getfile function in this script runs in anonymous ftp mode by defaultbut two-item tuple containing username and password string may be passed to the user argument in order to log in to the remote server in nonanonymous mode to use anonymous ftpeither don' pass the user argument or pass it an empty tuple(the ftp object login method allows two optional arguments to denote username and passwordand the function(*argscall syntax in example - sends it whatever argument tuple you pass to user as individual arguments processing modes if passedthe last two arguments (verboserefetchallow us to turn off status messages printed to the stdout stream (perhaps undesirable in gui contextand to force downloads to happen even if the file already exists locally (the download overwrites the existing local file client-side scripting
5,430
if used they must be passed by namenot position the user argument instead can be passed either wayif it is passed at all keyword-only arguments here prevent passed verbose or refetch values from being incorrectly matched against the user argument if the user value is actually omitted in call exception protocol the caller is expected to handle exceptionsthis function wraps downloads in try/finally statement to guarantee that the local output file is closedbut it lets exceptions propagate if used in gui or run from threadfor instanceexceptions may require special handling unknown in this file self-test if run standalonethis file downloads an image file again from my website as selftest (configure for your server and file as desired)but the function will normally be passed ftp filenamessite namesand directory names as well file mode as in earlier examplesthis script is careful to open the local output file in wb binary mode to suppress end-line mapping and conform to python ' unicode string model as we learned in it' not impossible that true binary datafiles may have bytes whose value is equal to \ line-feed characteropening in text mode instead would make these bytes automatically expand to \ \ two-byte sequence when written locally on windows this is only an issue when run on windowsmode doesn' change end-lines elsewhere as we also learned in thoughbinary mode is required to suppress the automatic unicode translations performed for text in python without binary modepython would attempt to encode fetched data when written per default or passed unicode encoding schemewhich might fail for some types of fetched text and would normally fail for truly binary data such as images and audio because retrbinary writes bytes strings in xwe really cannot open the output file in text mode anyhowor write will raise exceptions recall that in textmode files require str stringsand binary mode files expect bytes since retrbinary writes bytes and retrlines writes strthey implicitly require binary and text-mode output filesrespectively this constraint is irrespective of end-line or unicode issuesbut it effectively accomplishes those goals as well as we'll see in later examplestext-mode retrievals have additional encoding requirementsin factftplib will turn out to be good example of the impacts of python ' unicode string model on real-world code by always using binary mode in the script herewe sidestep the issue altogether directory model this function currently uses the same filename to identify both the remote file and the local file where the download should be stored as suchit should be run in the directory where you want the file to show upuse os chdir to move to directories if needed (we could instead assume filename is the local file' nameand transferring files with ftplib
5,431
distinct filename arguments--local and remote also notice thatdespite its namethis module is very different from the getfile py script we studied at the end of the sockets material in the preceding the socket-based getfile implemented custom client and server-side logic to download server file to client machine over raw sockets the new getfile here is client-side tool only instead of raw socketsit uses the standard ftp protocol to request file from serverall socket-level details are hidden in the simpler ftplib module' implementation of the ftp client protocol furthermorethe server here is perpetually running program on the server machinewhich listens for and responds to ftp requests on socketon the dedicated ftp port (number the net functional effect is that this script requires an ftp server to be running on the machine where the desired file livesbut such server is much more likely to be available upload utility while we're at itlet' write script to upload single file by ftp to remote machine the upload interfaces in the ftp module are symmetric with the download interfaces given connected ftp objectitsstorbinary method can be used to upload bytes from an open local file object storlines method can be used to upload text in ascii mode from an open local file object unlike the download interfacesboth of these methods are passed file object as wholenot file object method (or other functionwe will meet the storlines method in later example the utility module in example - uses storbinary such that the file whose name is passed in is always uploaded verbatim--in binary modewithout unicode encodings or line-feed translations for the target machine' conventions if this script uploads text fileit will arrive exactly as stored on the machine it came fromwith client line-feed markers and existing unicode encoding example - pp \internet\ftp\putfile py #!/usr/local/bin/python ""store an arbitrary file by ftp in binary mode uses anonymous ftp unless you pass in user=(namepswdtuple of arguments ""import ftplib socket-based ftp tools def putfile(filesitediruser=()*verbose=true)""store file by ftp to site/directory anonymous or real loginbinary transfer client-side scripting
5,432
if verboseprint('uploading'filelocal open(file'rb'local file of same name remote ftplib ftp(siteconnect to ftp site remote login(*useranonymous or real login remote cwd(dirremote storbinary('stor filelocal remote quit(local close(if verboseprint('upload done 'if __name__ ='__main__'site 'ftp rmi netdir import sysgetpass pswd getpass getpass(site pswd?'putfile(sys argv[ ]sitediruser=('lutz'pswd)filename on cmdline nonanonymous login notice that for portabilitythe local file is opened in rb binary input mode this time to suppress automatic line-feed character conversions if this is binary informationwe don' want any bytes that happen to have the value of the \ carriage-return character to mysteriously go away during the transfer when run on windows client we also want to suppress unicode encodings for nontext filesand we want reads to produce the bytes strings expected by the storbinary upload operation (more on input file modes laterthis script uploads file you name on the command line as self-testbut you will normally pass in real remote filenamesite nameand directory name strings also like the download utilityyou may pass (usernamepasswordtuple to the user argument to trigger nonanonymous ftp mode (anonymous ftp is the defaultplaying the monty python theme song it' time for bit of fun to testlet' use these scripts to transfer copy of the monty python theme song audio file have at my website firstlet' write module that downloads and plays the sample fileas shown in example - example - pp \internet\ftp\sousa py #!/usr/local/bin/python ""usagesousa py fetch and play the monty python theme song this will not work on your system as isit requires machine with internet access and an ftp server account you can accessand uses audio filters on unix and your au player on windows configure this and playfile py as needed for your platform ""from getpass import getpass from pp internet ftp getfile import getfile from pp system media playfile import playfile file 'sousa audefault file coordinates transferring files with ftplib
5,433
dir user ('lutz'getpass('pswd?')monty python theme song getfile(filesitediruserplayfile(filefetch audio file by ftp send it to audio player import os os system('getone py sousa au'equivalent command line there' not much to this scriptbecause it really just combines two tools we've already coded we're reusing example - ' getfile to downloadand ' play file module (example - to play the audio sample after it is downloaded (turn back to that example for more details on the player part of the taskalso notice the last two lines in this file--we can achieve the same effect by passing in the audio filename as command-line argument to our original scriptbut it' less direct as isthis script assumes my ftp server accountconfigure as desired (alasthis file used to be at the ftp python org anonymous ftp sitebut that site went dark for security reasons between editions of this bookonce configuredthis script will run on any machine with pythonan internet linkand recognizable audio playerit works on my windows laptop with broadband internet connectionand it plays the music clip in windows media player (and if could insert an audio file hyperlink here to show what it sounds likei would ) :\pp \internet\ftpsousa py pswddownloading sousa au download done :\pp \internet\ftpsousa py pswdsousa au already fetched the getfile and putfile modules themselves can be used to move the sample file around too both can either be imported by clients that wish to use their functionsor run as top-level programs to trigger self-tests and command-line usage for varietylet' run these scripts from command line and the interactive prompt to see how they work when run standalonethe filename is passed in the command line to putfile and both use password input and default site settingsc:\pp \internet\ftpputfile py sousa py ftp rmi net pswduploading sousa py upload done when importedparameters are passed explicitly to functionsc:\pp \internet\ftppython from getfile import getfile getfile(file='sousa au'site='ftp rmi net'dir='user=('lutz''xxx')sousa au already fetched client-side scripting
5,434
:\pp \internet\ftppython from getfile import getfile getfile(file='sousa au'site='ftp rmi net'dir='user=('lutz''xxx')downloading sousa au download done from pp system media playfile import playfile playfile('sousa au'although python' ftplib already automates the underlying socket and message formatting chores of ftptools of our own like these can make the process even simpler adding user interface if you read the preceding you'll recall that it concluded with quick look at scripts that added user interface to socket-based getfile script--one that transferred files over proprietary socket dialoginstead of over ftp at the end of that presentationi mentioned that ftp is much more generally useful way to move files around because ftp servers are so widely available on the net for illustration purposesexample - shows simple mutation of the prior user interfaceimplemented as new subclass of the preceding general form builderform py of example - example - pp \internet\ftp\getfilegui py ""################################################################################launch ftp getfile function with reusable form gui classuses os chdir to goto target local dir (getfile currently assumes that filename has no local directory path prefix)runs getfile getfile in thread to allow more than one to be running at once and avoid blocking gui during downloadsthis differs from socket-based getfileguibut reuses form gui builder toolsupports both user and anonymous ftp as currently codedcaveatsthe password field is not displayed as stars hereerrors are printed to the console instead of shown in the gui (threads can' generally update the gui on windows)this isn' thread safe (there is slight delay between os chdir here and opening the local output file in getfileand we could display both save-as popup for picking the local dirand remote directory listing for picking the file to getsuggested exercisesimprove me################################################################################""from tkinter import tkmainloop from tkinter messagebox import showinfo import getfileossys_thread from pp internet sockets form import form ftp getfile herenot socket reuse form tool in socket dir class ftpform(form)def __init__(self)root tk(transferring files with ftplib
5,435
labels ['server name''remote dir''file name''local dir''user name?''password?'form __init__(selflabelsrootself mutex _thread allocate_lock(self threads def transfer(selffilenameservernameremotediruserinfo)tryself do_transfer(filenameservernameremotediruserinfoprint('% of "%ssuccessful(self modefilename)exceptprint('% of "%shas failed:(self modefilename)end='print(sys exc_info()[ ]sys exc_info()[ ]self mutex acquire(self threads - self mutex release(def onsubmit(self)form onsubmit(selflocaldir self content['local dir'get(remotedir self content['remote dir'get(servername self content['server name'get(filename self content['file name'get(username self content['user name?'get(password self content['password?'get(userinfo (if username and passworduserinfo (usernamepasswordif localdiros chdir(localdirself mutex acquire(self threads + self mutex release(ftpargs (filenameservernameremotediruserinfo_thread start_new_thread(self transferftpargsshowinfo(self title'% of "%sstarted(self modefilename)def oncancel(self)if self threads = tk(quit(elseshowinfo(self title'cannot exit% threads runningself threadsclass ftpgetfileform(ftpform)title 'ftpgetfileguimode 'downloaddef do_transfer(selffilenameservernameremotediruserinfo)getfile getfilefilenameservernameremotediruserinfoverbose=falserefetch=trueif __name__ ='__main__'ftpgetfileform(mainloop( client-side scripting
5,436
in structure to its counterpart therein factit has the same name (and is distinct only because it lives in different directorythe class herethoughknows how to use the ftp-based getfile module from earlier in this instead of the socket-based getfile module we met ago when runthis version also implements more input fieldsas in figure - shown on windows figure - ftp getfile input form notice that full absolute file path can be entered for the local directory here if notthe script assumes the current working directorywhich changes after each download and can vary depending on where the gui is launched ( the current directory differs when this script is run by the pydemos program at the top of the examples treewhen we click this gui' submit button (or press the enter key)the script simply passes the form' input field values as arguments to the getfile getfile ftp utility function of example - earlier in this section it also posts pop up to tell us the download has begun (figure - figure - ftp getfile info pop up transferring files with ftplib
5,437
as well as one that fails (with added blank lines for readability) :\pp \internet\ftpgetfilegui py server name =ftp rmi net user name=lutz local dir =test file name =about-pp html password=xxxxxxxx remote dir =download of "about-pp htmlsuccessful server name =ftp rmi net user name=lutz local dir = :\temp file name =ora-lp -big jpg password=xxxxxxxx remote dir =download of "ora-lp -big jpgsuccessful server name =ftp rmi net user name=lutz local dir = :\temp file name =ora-lp jpg password=xxxxxxxx remote dir =download of "ora-lp jpghas failed ora-lp jpgno such file or directory given username and passwordthe downloader logs into the specified account to do anonymous ftp insteadleave the username and password fields blank nowto illustrate the threading capabilities of this guistart download of large filethen start another download while this one is in progress the gui stays active while downloads are underwayso we simply change the input fields and press submit again this second download starts and runs in parallel with the firstbecause each download is run in threadand more than one internet connection can be active at once in factthe gui itself stays active during downloads only because downloads are run in threadsif they were noteven screen redraws wouldn' happen until download finished we discussed threads in and their application to guis in and but this script illustrates some practical thread concernsthis program takes care to not do anything gui-related in download thread as we've learnedonly the thread that makes guis can generally process them to avoid killing spawned download threads on some platformsthe gui must also be careful not to exit while any downloads are in progress it keeps track of the number of in-progress threadsand just displays pop up if we try to kill the gui by pressing the cancel button while both of these downloads are in progress client-side scripting
5,438
we will apply such techniques when we explore the pymailgui example in the next to be portablethoughwe can' really close the gui until the active-thread count falls to zerothe exit model of the threading module of can be used to achieve the same effect here is the sort of output that appears in the console window when two downloads overlap in timec:\pp \internet\ftppython getfilegui py server name =ftp rmi net user name=lutz local dir = :\temp file name =spain jpg password=xxxxxxxx remote dir =server name user namelocal dir file name passwordremote dir ======ftp rmi net lutz :\temp index html xxxxxxxx download of "index htmlsuccessful download of "spain jpgsuccessful this example isn' much more useful than command line-based toolof coursebut it can be easily modified by changing its python codeand it provides enough of gui to qualify as simplefirst-cut ftp user interface moreoverbecause this gui runs downloads in python threadsmore than one can be run at the same time from this gui without having to start or restart different ftp client tool while we're in gui moodlet' add simple interface to the putfile utilitytoo the script in example - creates dialog that starts uploads in threadsusing core ftp logic imported from example - it' almost the same as the getfile gui we just wroteso there' not much new to say in factbecause get and put operations are so similar from an interface perspectivemost of the get form' logic was deliberately factored out into single generic class (ftpform)so changes need be made in only single place that isthe put gui here is mostly just reuse of the get guiwith distinct output labels and transfer methods it' in file by itselfthoughto make it easy to launch as standalone program example - pp \internet\ftp\putfilegui py ""##############################################################launch ftp putfile function with reusable form gui classsee getfilegui for notesmost of the same caveats applythe get and put forms have been factored into single class such that changes need be made in only one place##############################################################""transferring files with ftplib
5,439
import putfilegetfilegui class ftpputfileform(getfilegui ftpform)title 'ftpputfileguimode 'uploaddef do_transfer(selffilenameservernameremotediruserinfo)putfile putfile(filenameservernameremotediruserinfoverbose=falseif __name__ ='__main__'ftpputfileform(mainloop(running this script looks much like running the download guibecause it' almost entirely the same code at work let' upload some files from the client machine to the serverfigure - shows the state of the gui while starting one figure - ftp putfile input form and here is the console window output we get when uploading two files in serial fashionhere againuploads run in parallel threadsso if we start new upload before one in progress is finishedthey overlap in timec:\pp \internet\ftp\test\putfilegui py server name =ftp rmi net user name=lutz local dir =file name =sousa au password=xxxxxxxx remote dir =upload of "sousa ausuccessful server name user namelocal dir file name ====ftp rmi net lutz about-pp html client-side scripting
5,440
=xxxxxxxx remote dir =upload of "about-pp htmlsuccessful finallywe can bundle up both guis in single launcher script that knows how to start the get and put interfacesregardless of which directory we are in when the script is startedand independent of the platform on which it runs example - shows this process example - pp \internet\ftp\pyftpgui pyw ""spawn ftp get and put guis no matter what directory ' run fromos getcwd is not necessarily the place this script livescould also hardcode path from $pp ehomeor guesslocationcould also do[from pp launchmodes import portablelauncherportablelauncher('getfilegui''% /getfilegui pymydir)()]but need the dos console pop up on windows to view status messages which describe transfers made""import ossys print('running in'os getcwd()pp from pp launcher import findfirst mydir os path split(findfirst(os curdir'pyftpgui pyw'))[ pp from pp tools find import findlist mydir os path dirname(findlist('pyftpgui pyw'startdir=os curdir)[ ]if sys platform[: ='win'os system('start % \getfilegui pymydiros system('start % \putfilegui pymydirelseos system('python % /getfilegui py &mydiros system('python % /putfilegui py &mydirnotice that we're reusing the find utility from ' example - again here-this time to locate the home directory of the script in order to build command lines when run by launchers in the examples root directory or command lines elsewhere in generalthe current working directory may not always be this script' container in the prior editionthis script used tool in the launcher module instead to search for its own directory (see the examples distribution for that equivalentwhen this script is startedboth the get and put guis appear as distinctindependently run programsalternativelywe might attach both forms to single interface we could get much fancier than these two interfacesof course for instancewe could pop up local file selection dialogsand we could display widgets that give the status of downloads and uploads in progress we could even list files available at the remote site in selectable listbox by requesting remote directory listings over the ftp connection to learn how to add features like thatthoughwe need to move on to the next section transferring files with ftplib
5,441
once upon timei used telnet to manage my website at my internet service provider (ispi logged in to the web server in shell windowand performed all my edits directly on the remote machine there was only one copy of site' files--on the machine that hosted it moreovercontent updates could be performed from any machine that ran telnet client--ideal for people with travel-based careers of coursetimes have changed like most personal websitestoday mine are maintained on my laptop and transfer their files to and from my isp as needed oftenthis is simple matter of one or two filesand it can be accomplished with command-line ftp client sometimesthoughi need an easy way to transfer the entire site maybe need to download to detect files that have become out of sync occasionallythe changes are so involved that it' easier to upload the entire site in single step although there are variety of ways to approach this task (including options in sitebuilder tools)python can help heretoowriting python scripts to automate the upload and download tasks associated with maintaining my website on my laptop provides portable and mobile solution because python ftp scripts will work on any machine with socketsthey can be run on my laptop and on nearly any other computer where python is installed furthermorethe same scripts used to transfer page files to and from my pc can be used to copy my site to another web server as backup copyshould my isp experience an outage the effect is sometimes called mirror-- copy of remote site downloading site directories the following two scripts address these needs the firstdownloadflat pyautomatically downloads ( copiesby ftp all the files in directory at remote site to directory on the local machine keep the main copy of my website files on my pc these daysbut use this script in two waysto download my website to client machines where want to make editsi fetch the contents of my web directory of my account on my isp' machine to mirror my site to my account on another serveri run this script periodically on the target machine if it supports telnet or ssh secure shellif it does noti simply download to one machine and upload from there to the target server noreally the second edition of this book included tale of woe here about how my isp forced its users to wean themselves off telnet access this seems like small issue today common practice on the internet has come far in short time one of my sites has even grown too complex for manual edits (exceptof courseto work around bugs in the site-builder toolcome to think of itso has python' presence on the web when first found python in it was set of encoded email messageswhich users decoded and concatenated and hoped the result worked yesyesi know--geegrandpatell us more client-side scripting
5,442
files to any machine with python and socketsfrom any machine running an ftp server example - pp \internet\ftp\mirror\downloadflat py #!/bin/env python ""##############################################################################use ftp to copy (downloadall files from single directory at remote site to directory on the local machinerun me periodically to mirror flat ftp site directory to your isp accountset user to 'anonymousto do anonymous ftpwe could use try to skip file failuresbut the ftp connection is likely closed if any files failwe could also try to reconnect with new ftp instance before each transferconnects once nowif failurestry setting nonpassive for active ftpor disable firewallsthis also depends on working ftp serverand possibly its load policies ##############################################################################""import ossysftplib from getpass import getpass from mimetypes import guess_type nonpassive false passive ftp on by default in remotesite 'home rmi netdownload from this site remotedir and this dir ( public_htmlremoteuser 'lutzremotepass getpass('password for % on % (remoteuserremotesite)localdir (len(sys argv and sys argv[ ]or cleanall input('clean local directory first')[: in [' '' 'print('connecting 'connection ftplib ftp(remotesiteconnection login(remoteuserremotepassconnection cwd(remotedirif nonpassiveconnection set_pasv(falseconnect to ftp site login as user/password cd to directory to copy force active mode ftp most servers do passive if cleanallfor localname in os listdir(localdir)try to delete all locals tryfirstto remove old files print('deleting local'localnameos listdir omits and os remove(os path join(localdirlocalname)exceptprint('cannot delete local'localnamecount remotefiles connection nlst(for remotename in remotefilesif remotename in ('')continue mimetypeencoding guess_type(remotenamemimetype mimetype or '?/?maintype mimetype split('/')[ download all remote files nlst(gives files list dir(gives full details some servers include and ('text/plain''gzip'may be (nonenonejpg ('image/jpeg'none'transferring directories with ftplib
5,443
print('downloading'remotename'to'localpathend='print('as'maintypeencoding or ''if maintype ='textand encoding =noneuse ascii mode xfer and text file use encoding compatible wth ftplib' localfile open(localpath' 'encoding=connection encodingcallback lambda linelocalfile write(line '\ 'connection retrlines('retr remotenamecallbackelseuse binary mode xfer and bytes file localfile open(localpath'wb'connection retrbinary('retr remotenamelocalfile writelocalfile close(count + connection quit(print('done:'count'files downloaded 'there' not much that is new to speak of in this scriptcompared to other ftp examples we've seen thus far we open connection with the remote ftp serverlog in with username and password for the desired account (this script never uses anonymous ftp)and go to the desired remote directory new herethoughare loops to iterate over all the files in local and remote directoriestext-based retrievalsand file deletionsdeleting all local files this script has cleanall optionenabled by an interactive prompt if selectedthe script first deletes all the files in the local directory before downloadingto make sure there are no extra files that aren' also on the server (there may be junk here from prior downloadto delete local filesthe script calls os listdir to get list of filenames in the directoryand os remove to delete eachsee (or the python library manualfor more details if you've forgotten what these calls do notice the use of os path join to concatenate directory path and filename according to the host platform' conventionsos listdir returns filenames without their directory pathsand this script is not necessarily run in the local directory where downloads will be placed the local directory defaults to the current directory (")but can be set differently with command-line argument to the script fetching all remote files to grab all the files in remote directorywe first need list of their names the ftp object' nlst method is the remote equivalent of os listdirnlst returns list of the string names of all files in the current remote directory once we have this listwe simply step through it in looprunning ftp retrieval commands for each filename in turn (more on this in minutethe nlst method ismore or lesslike requesting directory listing with an ls command in typical interactive ftp programsbut python automatically splits up client-side scripting
5,444
listedby default it lists the current server directory related ftp methoddirreturns the list of line strings produced by an ftp list commandits result is like typing dir command in an ftp sessionand its lines contain complete file informationunlike nlst if you need to know more about all the remote filesparse the result of dir method call (we'll see how in later examplenotice how we skip and current and parent directory indicators if present in remote directory listingsunlike os listdirsome (but not allservers include theseso we need to either skip these or catch the exceptions they may trigger (more on this later when we start using dirtooselecting transfer modes with mimetypes we discussed output file modes for ftp earlierbut now that we've started transferring texttooi can fill in the rest of this story to handle unicode encodings and to keep line-ends in sync with the machines that my web files live onthis script distinguishes between binary and text file transfers it uses the python mimetypes module to choose between text and binary transfer modes for each file we met mimetypes in near example - where we used it to play media files (see the examples and description there for an introductionheremime types is used to decide whether file is text or binary by guessing from its filename extension for instancehtml web pages and simple text files are transferred as text with automatic line-end mappingsand images and tar archives are transferred in raw binary mode downloadingtext versus binary for binary files data is pulled down with the retrbinary method we met earlierand stored in local file with binary open mode of wb this file open mode is required to allow for the bytes strings passed to the write method by retrbinarybut it also suppresses line-end byte mapping and unicode encodings in the process againtext mode requires encodable text in python xand this fails for binary data like images this script may also be run on windows or unix-like platformsand we don' want \ byte embedded in an image to get expanded to \ \ on windows we don' use chunk-size third argument for binary transfers herethough--it defaults to reasonable size if omitted for text filesthe script instead uses the retrlines methodpassing in function to be called for each line in the text file downloaded the text line handler function receives lines in str string formand mostly just writes the line to local text file but notice that the handler function created by the lambda here also adds \ lineend character to the end of the line it is passed python' retrlines method strips all line-feed characters from lines to sidestep platform differences by adding \nthe script ensures the proper line-end marker character sequence for the local platform on which this script runs when written to the file (\ or \ \nfor this auto-mapping of the \ in the script to workof coursewe must also open text output files in text modenot in wb--the mapping from \ to \ \ on transferring directories with ftplib
5,445
also means that the file' write method will allow for the str string passed in by retrlinesand that text will be encoded per unicode when written subtlythoughwe also explicitly use the ftp connection object' unicode encoding scheme for our text output file in openinstead of the default without this encoding optionthe script aborted with unicodeencodeerror exception for some files in my site in retrlinesthe ftp object itself reads the remote file data over socket with text-mode file wrapper and an explicit encoding scheme for decodingsince the ftp object can do no better than this encoding anyhowwe use its encoding for our output file as well by defaultftp objects use the latin scheme for decoding text fetched (as well as for encoding text sent)but this can be specialized by assigning to their encoding attribute our script' local text output file will inherit whatever encoding ftplib uses and so be compatible with the encoded text data that it produces and passes we could try to also catch unicode exceptions for files outside the unicode encoding used by the ftp objectbut exceptions leave the ftp object in an unrecoverable state in tests 've run in python alternativelywe could use wb binary mode for the local text output file and manually encode line strings with line encodeor simply use retrbinary and binary mode files in all casesbut both of these would fail to map end-lines portably--the whole point of making text distinct in this context all of this is simpler in action than in words here is the command use to download my entire book support website from my isp server account to my windows laptop pcin single stepc:\pp \internet\ftp\mirrordownloadflat py test password for lutz on home rmi netclean local directory firsty connecting deleting local -longmont-classes html deleting local -longmont-classes html deleting local -longmont-classes html deleting local about-hopl html deleting local about-lp html deleting local about-lp html deleting local about-pp-japan html lines omitted downloading -longmont-classes html to test\ -longmont-classes html as text downloading -longmont-classes html to test\ -longmont-classes html as text downloading -longmont-classes html to test\ -longmont-classes html as text downloading about-hopl html to test\about-hopl html as text downloading about-lp html to test\about-lp html as text downloading about-lp html to test\about-lp html as text downloading about-pp-japan html to test\about-pp-japan html as text client-side scripting
5,446
downloading ora-pyref gif to test\ora-pyref gif as image downloading ora-lp -big jpg to test\ora-lp -big jpg as image downloading ora-lp gif to test\ora-lp gif as image downloading pyref -updates html to test\pyref -updates html as text downloading lp -updates html to test\lp -updates html as text downloading lp -examples html to test\lp -examples html as text downloading lp -examples zip to test\lp -examples zip as application done files downloaded this may take few moments to completedepending on your site' size and your connection speed (it' bound by network speed constraintsand it usually takes roughly two to three minutes for my site on my current laptop and wireless broadband connectionit is much more accurate and easier than downloading files by handthough the script simply iterates over all the remote files returned by the nlst methodand downloads each with the ftp protocol ( over socketsin turn it uses text transfer mode for names that imply text dataand binary mode for others with the script running this wayi make sure the initial assignments in it reflect the machines involvedand then run the script from the local directory where want the site copy to be stored because the target download directory is often not where the script livesi may need to give python the full path to the script file when run on server in telnet or ssh session windowfor instancethe execution and script directory paths are differentbut the script works the same way if you elect to delete local files in the download directoryyou may also see batch of "deleting local messages scroll by on the screen before any "downloading lines appearthis automatically cleans out any garbage lingering from prior download and if you botch the input of the remote site passworda python exception is raisedi sometimes need to run it again (and type more slowly) :\pp \internet\ftp\mirrordownloadflat py test password for lutz on home rmi netclean local directory firstconnecting traceback (most recent call last)file " :\pp \internet\ftp\mirror\downloadflat py"line in connection login(remoteuserremotepasslogin as user/password file " :\python \lib\ftplib py"line in login if resp[ =' 'resp self sendcmd('pass passwdfile " :\python \lib\ftplib py"line in sendcmd return self getresp(file " :\python \lib\ftplib py"line in getresp raise error_perm(respftplib error_perm login incorrect it' worth noting that this script is at least partially configured by assignments near the top of the file in additionthe password and deletion options are given by interactive inputsand one command-line argument is allowed--the local directory name to store transferring directories with ftplib
5,447
command-line arguments could be employed to universally configure all the other download parameters and optionstoobut because of python' simplicity and lack of compile/link stepschanging settings in the text of python scripts is usually just as easy as typing words on command line to check for version skew after batch of downloads and uploadsyou can run the diffall script we wrote in example - for instancei find files that have diverged over time due to updates on multiple platforms by comparing the download to local copy of my website using shell command line such as :\pp \internet \ftp\system\filetools\diffall py mirror\test :\web sites\public_html see for more details on this tooland file diffall out txt in the diffs subdirectory of the examples distribution for sample runits text file differences stem from either final line newline characters or newline differences reflecting binary transfers that windows fc commands and ftp servers do not notice uploading site directories uploading full directory is symmetric to downloadingit' mostly matter of swapping the local and remote machines and operations in the program we just met the script in example - uses ftp to copy all files in directory on the local machine on which it runs up to directory on remote machine really use this scripttoomost often to upload all of the files maintained on my laptop pc to my isp account in one fell swoop also sometimes use it to copy my site from my pc to mirror machine or from the mirror machine back to my isp because this script runs on any computer with python and socketsit happily transfers directory from any machine on the net to any machine running an ftp server simply change the initial setting in this module as appropriate for the transfer you have in mind example - pp \internet\ftp\mirror\uploadflat py #!/bin/env python ""#############################################################################use ftp to upload all files from one local dir to remote site/directorye run me to copy web/ftp site' files from your pc to your ispassumes flat directory uploaduploadall py does nested directories see downloadflat py comments for more notesthis script is symmetric #############################################################################""import ossysftplib from getpass import getpass from mimetypes import guess_type client-side scripting
5,448
passive ftp by default remotesite 'learning-python comupload to this site remotedir 'booksfrom machine running on remoteuser 'lutzremotepass getpass('password for % on % (remoteuserremotesite)localdir (len(sys argv and sys argv[ ]or cleanall input('clean remote directory first')[: in [' '' 'print('connecting 'connection ftplib ftp(remotesiteconnection login(remoteuserremotepassconnection cwd(remotedirif nonpassiveconnection set_pasv(falseconnect to ftp site log in as user/password cd to directory to copy force active mode ftp most servers do passive if cleanallfor remotename in connection nlst()try to delete all remotes tryfirstto remove old files print('deleting remote'remotenameconnection delete(remotenameskips and if attempted exceptprint('cannot delete remote'remotenamecount localfiles os listdir(localdirfor localname in localfilesmimetypeencoding guess_type(localnamemimetype mimetype or '?/?maintype mimetype split('/')[ upload all local files listdir(strips dir path any failure ends script ('text/plain''gzip'may be (nonenonejpg ('image/jpeg'none'localpath os path join(localdirlocalnameprint('uploading'localpath'to'localnameend='print('as'maintypeencoding or ''if maintype ='textand encoding =noneuse ascii mode xfer and bytes file need rb mode for ftplib' crlf logic localfile open(localpath'rb'connection storlines('stor localnamelocalfileelseuse binary mode xfer and bytes file localfile open(localpath'rb'connection storbinary('stor localnamelocalfilelocalfile close(count + connection quit(print('done:'count'files uploaded 'transferring directories with ftplib
5,449
interfaces and set of ftp scripting techniquesdeleting all remote files just like the mirror scriptthe upload begins by asking whether we want to delete all the files in the remote target directory before copying any files there this cleanall option is useful if we've deleted files in the local copy of the directory in the client--the deleted files would remain on the server-side copy unless we delete all files there first to implement the remote cleanupthis script simply gets listing of all the files in the remote directory with the ftp nlst methodand deletes each in turn with the ftp delete method assuming we have delete permissionthe directory will be emptied (file permissions depend on the account we logged into when connecting to the serverwe've already moved to the target remote directory when deletions occurso no directory paths need to be prepended to filenames here note that nlst may raise an exception for some servers if the remote directory is emptywe don' catch the exception herebut you can simply not select cleaning if one fails for you we do catch deletion exceptionsbecause directory names like and may be returned in the listing by some servers storing all local files to apply the upload operation to each file in the local directorywe get list of local filenames with the standard os listdir calland take care to prepend the local source directory path to each filename with the os path join call recall that os listdir returns filenames without directory pathsand the source directory may not be the same as the script' execution directory if passed on the command line uploadingtext versus binary this script may also be run on both windows and unix-like clientsso we need to handle text files specially like the mirror downloadthis script picks text or binary transfer modes by using python' mimetypes module to guess file' type from its filename extensionhtml and text files are moved in ftp text modefor instance we already met the storbinary ftp object method used to upload files in binary mode--an exactbyte-for-byte copy appears at the remote site text-mode transfers work almost identicallythe storlines method accepts an ftp command string and local file (or file-likeobjectand simply copies each line read from the local file to same-named file on the remote machine noticethoughthat the local text input file must be opened in rb binary mode in python text input files are normally opened in text mode to perform unicode decoding and to convert any \ \ end-of-line sequences on windows to the \ platform-neutral character as lines are read howeverftplib in python requires that the text file be opened in rb binary modebecause it converts all end-lines to the \ \ sequence for transmissionto do soit must read lines as raw bytes with readlines and perform bytes string processingwhich implies binary mode files client-side scripting
5,450
because there was no separate bytes type\ was expanded to \ \ opening the local file in binary mode for ftplib to read also means no unicode decoding will occurthe text is sent over sockets as byte string in already encoded form all of which isof coursea prime lesson on the impacts of unicode encodingsconsult the module ftplib py in the python source library directory for more details for binary mode transfersthings are simpler--we open the local file in rb binary mode to suppress unicode decoding and automatic mapping everywhereand return the bytes strings expected by ftplib on read binary data is not unicode textand we don' want bytes in an audio file that happen to have the same value as \ to magically disappear when read on windows as for the mirror download scriptthis program simply iterates over all files to be transferred (files in the local directory listing this time)and transfers each in turn--in either text or binary modedepending on the filesnames here is the command use to upload my entire website from my laptop windows pc to remote linux server at my ispin single stepc:\pp \internet\ftp\mirroruploadflat py test password for lutz on learning-python comclean remote directory firsty connecting deleting remote cannot delete remote deleting remote cannot delete remote deleting remote -longmont-classes html deleting remote -longmont-classes html deleting remote -longmont-classes html deleting remote about-lp html deleting remote about-lp html deleting remote about-lp html deleting remote about-lp html lines omitted uploading test\ -longmont-classes html to -longmont-classes html as text uploading test\ -longmont-classes html to -longmont-classes html as text uploading test\ -longmont-classes html to -longmont-classes html as text uploading test\about-lp html to about-lp html as text uploading test\about-lp html to about-lp html as text uploading test\about-lp html to about-lp html as text uploading test\about-lp html to about-lp html as text uploading test\about-pp-japan html to about-pp-japan html as text lines omitted uploading test\whatsnew html to whatsnew html as text uploading test\whatsold html to whatsold html as text uploading test\wxpython doc tgz to wxpython doc tgz as application gzip uploading test\xlate-lp html to xlate-lp html as text transferring directories with ftplib
5,451
uploading test\zaurus jpg to zaurus jpg as image uploading test\zaurus jpg to zaurus jpg as image uploading test\zoo-jan- jpg to zoo-jan- jpg as image uploading test\zopeoutline htm to zopeoutline htm as text done files uploaded for my site and on my current laptop and wireless broadband connectionthis process typically takes six minutesdepending on server load as with the download scripti often run this command from the local directory where my web files are keptand pass python the full path to the script when run this on linux serverit works in the same waybut the paths to the script and my web files directory differ +refactoring uploads and downloads for reuse the directory upload and download scripts of the prior two sections work as advertised andapart from the mimetypes logicwere the only ftp examples that were included in the second edition of this book if you look at these two scripts long enoughthoughtheir similarities will pop out at you eventually in factthey are largely the same--they use identical code to configure transfer parametersconnect to the ftp serverand determine file type the exact details have been lost to timebut some of this code was certainly copied from one file to the other although such redundancy isn' cause for alarm if we never plan on changing these scriptsit can be killer in software projects in general when you have two copies of identical bits of codenot only is there danger of them becoming out of sync over time (you'll lose uniformity in user interface and behavior)but you also effectively double your effort when it comes time to change code that appears in both places unless you're big fan of extra workit pays to avoid redundancy wherever possible this redundancy is especially glaring when we look at the complex code that uses mimetypes to determine file types repeating magic like this in more than one place is almost always bad idea--not only do we have to remember how it works every time we need the same utilitybut it is recipe for errors refactoring with functions as originally codedour download and upload scripts comprise top-level script code that relies on global variables such structure is difficult to reuse--code runs immediately on importsand it' difficult to generalize for varying contexts worseit' difficult to maintain--when you program by cut-and-paste of existing codeyou increase the cost of future changes every time you click the paste button +usage notethese scripts are highly dependent on the ftp server functioning properly for whilethe upload script occasionally had timeout errors when running over my current broadband connection these errors went away laterwhen my isp fixed or reconfigured their server if you have failurestry running against different serverconnecting and disconnecting around each transfer may or may not help (some servers limit their number of connections client-side scripting
5,452
(reorganizethe download script by wrapping its parts in functionsthey become reusable in other modulesincluding our upload program example - pp \internet\ftp\mirror\downloadflat_modular py #!/bin/env python ""#############################################################################use ftp to copy (downloadall files from remote site and directory to directory on the local machinethis version works the samebut has been refactored to wrap up its code in functions that can be reused by the uploaderand possibly other programs in the future else code redundancywhich may make the two diverge over timeand can double maintenance costs #############################################################################""import ossysftplib from getpass import getpass from mimetypes import guess_typeadd_type defaultsite 'home rmi netdefaultrdir defaultuser 'lutzdef configtransfer(site=defaultsiterdir=defaultrdiruser=defaultuser)""get upload or download parameters uses class due to the large number ""class cfpass cf nonpassive false passive ftp on by default in cf remotesite site transfer to/from this site cf remotedir rdir and this dir (means acct rootcf remoteuser user cf localdir (len(sys argv and sys argv[ ]or cf cleanall input('clean target directory first')[: in [' ',' 'cf remotepass getpass'password for % on % :(cf remoteusercf remotesite)return cf def istextkind(remotenametrace=true)""use mimetype to guess if filename means text or binary for ' htmlguess is ('text/html'none)text for ' jpegguess is ('image/jpeg'none)binary for ' txt gzguess is ('text/plain''gzip')binary for unknownsguess may be (nonenone)binary mimetype can also guess name from typesee pymailgui ""add_type('text/ -python-win'pyw'mimetypeencoding guess_type(remotenamestrict=falsemimetype mimetype or '?/?maintype mimetype split('/')[ if traceprint(maintypeencoding or ''not in tables allow extras type unknownget first part transferring directories with ftplib
5,453
def connectftp(cf)print('connecting 'connection ftplib ftp(cf remotesiteconnection login(cf remoteusercf remotepassconnection cwd(cf remotedirif cf nonpassiveconnection set_pasv(falsereturn connection not compressed connect to ftp site log in as user/password cd to directory to xfer force active mode ftp most servers do passive def cleanlocals(cf)""try to delete all locals files first to remove garbage ""if cf cleanallfor localname in os listdir(cf localdir)local dirlisting trylocal file delete print('deleting local'localnameos remove(os path join(cf localdirlocalname)exceptprint('cannot delete local'localnamedef downloadall(cfconnection)""download all files from remote site/dir per cf config ftp nlst(gives files listdir(gives full details ""remotefiles connection nlst(nlst is remote listing for remotename in remotefilesif remotename in ('')continue localpath os path join(cf localdirremotenameprint('downloading'remotename'to'localpath'as'end='if istextkind(remotename)use text mode xfer localfile open(localpath' 'encoding=connection encodingdef callback(line)localfile write(line '\ 'connection retrlines('retr remotenamecallbackelseuse binary mode xfer localfile open(localpath'wb'connection retrbinary('retr remotenamelocalfile writelocalfile close(connection quit(print('done:'len(remotefiles)'files downloaded 'if __name__ ='__main__'cf configtransfer(conn connectftp(cfcleanlocals(cfdownloadall(cfconndon' delete if can' connect compare this version with the original this scriptand every other in this sectionruns the same as the original flat download and upload programs although we haven' client-side scripting
5,454
its code is now set of tools that can be imported and reused in other programs the refactored upload program in example - for instanceis now noticeably simplerand the code it shares with the download script only needs to be changed in one place if it ever requires improvement example - pp \internet\ftp\mirror\uploadflat_modular py #!/bin/env python ""#############################################################################use ftp to upload all files from local dir to remote site/directorythis version reuses downloader' functionsto avoid code redundancy#############################################################################""import os from downloadflat_modular import configtransferconnectftpistextkind def cleanremotes(cfconnection)""try to delete all remote files first to remove garbage ""if cf cleanallfor remotename in connection nlst()remote dir listing tryremote file delete print('deleting remote'remotenameskips and exc connection delete(remotenameexceptprint('cannot delete remote'remotenamedef uploadall(cfconnection)""upload all files to remote site/dir per cf config listdir(strips dir pathany failure ends script ""localfiles os listdir(cf localdirlistdir is local listing for localname in localfileslocalpath os path join(cf localdirlocalnameprint('uploading'localpath'to'localname'as'end='if istextkind(localname)use text mode xfer localfile open(localpath'rb'connection storlines('stor localnamelocalfileelseuse binary mode xfer localfile open(localpath'rb'connection storbinary('stor localnamelocalfilelocalfile close(connection quit(print('done:'len(localfiles)'files uploaded 'if __name__ ='__main__'cf configtransfer(site='learning-python com'rdir='books'user='lutz'transferring directories with ftplib
5,455
cleanremotes(cfconnuploadall(cfconnnot only is the upload script simpler now because it reuses common codebut it will also inherit any changes made in the download module for instancethe istextkind function was later augmented with code that adds the pyw extension to mimetypes tables (this file type is not recognized by default)because it is shared functionthe change is automatically picked up in the upload programtoo this script and the one it imports achieve the same goals as the originalsbut changing them for easier code maintenance is big deal in the real world of software development the followingfor exampledownloads the site from one server and uploads to anotherc:\pp \internet\ftp\mirrorpython downloadflat_modular py test clean target directory firstpassword for lutz on home rmi netconnecting downloading -longmont-classes html to test\ -longmont-classes html as text lines omitted downloading relo-feb -index html to test\relo-feb -index html as text done files downloaded :\pp \internet\ftp\mirrorpython uploadflat_modular py test clean target directory firstpassword for lutz on learning-python comconnecting uploading test\ -longmont-classes html to -longmont-classes html as text lines omitted uploading test\zopeoutline htm to zopeoutline htm as text done files uploaded refactoring with classes the function-based approach of the last two examples addresses the redundancy issuebut they are perhaps clumsier than they need to be for instancetheir cf configuration options object provides namespace that replaces global variables and breaks crossfile dependencies once we start making objects to model namespacesthoughpython' oop support tends to be more natural structure for our code as one last twistexample - refactors the ftp code one more time in order to leverage python' class feature example - pp \internet\ftp\mirror\ftptools py #!/bin/env python ""#############################################################################use ftp to download or upload all files in single directory from/to remote site and directorythis version has been refactored to use classes and oop for namespace and natural structurewe could also structure this as download superclassand an upload subclass which redefines the clean and transfer methodsbut then there is no easy way for another client to client-side scripting
5,456
othersalso make single file upload/download code in orig loops methods#############################################################################""import ossysftplib from getpass import getpass from mimetypes import guess_typeadd_type defaults for all clients dfltsite 'home rmi netdfltrdir dfltuser 'lutzclass ftptoolsallow these to be redefined def getlocaldir(self)return (len(sys argv and sys argv[ ]or def getcleanall(self)return input('clean target dir first?')[: in [' ',' 'def getpassword(self)return getpass'password for % on % :(self remoteuserself remotesite)def configtransfer(selfsite=dfltsiterdir=dfltrdiruser=dfltuser)""get upload or download parameters from module defaultsargsinputscmdline anonymous ftpuser='anonymouspass=emailaddr ""self nonpassive false passive ftp on by default in self remotesite site transfer to/from this site self remotedir rdir and this dir (means acct rootself remoteuser user self localdir self getlocaldir(self cleanall self getcleanall(self remotepass self getpassword(def istextkind(selfremotenametrace=true)""use mimetypes to guess if filename means text or binary for ' htmlguess is ('text/html'none)text for ' jpegguess is ('image/jpeg'none)binary for ' txt gzguess is ('text/plain''gzip')binary for unknownsguess may be (nonenone)binary mimetypes can also guess name from typesee pymailgui ""add_type('text/ -python-win'pyw'not in tables mimetypeencoding guess_type(remotenamestrict=false)allow extras mimetype mimetype or '?/?type unknownmaintype mimetype split('/')[ get st part if traceprint(maintypeencoding or ''transferring directories with ftplib
5,457
not compressed def connectftp(self)print('connecting 'connection ftplib ftp(self remotesiteconnect to ftp site connection login(self remoteuserself remotepasslog in as user/pswd connection cwd(self remotedircd to dir to xfer if self nonpassiveforce active mode connection set_pasv(falsemost do passive self connection connection def cleanlocals(self)""try to delete all local files first to remove garbage ""if self cleanallfor localname in os listdir(self localdir)local dirlisting trylocal file delete print('deleting local'localnameos remove(os path join(self localdirlocalname)exceptprint('cannot delete local'localnamedef cleanremotes(self)""try to delete all remote files first to remove garbage ""if self cleanallfor remotename in self connection nlst()remote dir listing tryremote file delete print('deleting remote'remotenameself connection delete(remotenameexceptprint('cannot delete remote'remotenamedef downloadone(selfremotenamelocalpath)""download one file by ftp in text or binary mode local name need not be same as remote name ""if self istextkind(remotename)localfile open(localpath' 'encoding=self connection encodingdef callback(line)localfile write(line '\ 'self connection retrlines('retr remotenamecallbackelselocalfile open(localpath'wb'self connection retrbinary('retr remotenamelocalfile writelocalfile close(def uploadone(selflocalnamelocalpathremotename)""upload one file by ftp in text or binary mode remote name need not be same as local name ""if self istextkind(localname) client-side scripting
5,458
self connection storlines('stor remotenamelocalfileelselocalfile open(localpath'rb'self connection storbinary('stor remotenamelocalfilelocalfile close(def downloaddir(self)""download all files from remote site/dir per config ftp nlst(gives files listdir(gives full details ""remotefiles self connection nlst(nlst is remote listing for remotename in remotefilesif remotename in ('')continue localpath os path join(self localdirremotenameprint('downloading'remotename'to'localpath'as'end='self downloadone(remotenamelocalpathprint('done:'len(remotefiles)'files downloaded 'def uploaddir(self)""upload all files to remote site/dir per config listdir(strips dir pathany failure ends script ""localfiles os listdir(self localdirlistdir is local listing for localname in localfileslocalpath os path join(self localdirlocalnameprint('uploading'localpath'to'localname'as'end='self uploadone(localnamelocalpathlocalnameprint('done:'len(localfiles)'files uploaded 'def run(selfcleantarget=lambda:nonetransferact=lambda:none)""run complete ftp session default clean and transfer are no-ops don' delete if can' connect to server ""self connectftp(cleantarget(transferact(self connection quit(if __name__ ='__main__'ftp ftptools(xfermode 'downloadif len(sys argv xfermode sys argv pop( get+del nd arg if xfermode ='download'ftp configtransfer(ftp run(cleantarget=ftp cleanlocalstransferact=ftp downloaddirelif xfermode ='upload'ftp configtransfer(site='learning-python com'rdir='books'user='lutz'ftp run(cleantarget=ftp cleanremotestransferact=ftp uploaddirtransferring directories with ftplib
5,459
print('usageftptools py ["download"upload"[localdir]'in factthis last mutation combines uploads and downloads into single filebecause they are so closely related as beforecommon code is factored into methods to avoid redundancy new herethe instance object itself becomes natural namespace for storing configuration options (they become self attributesstudy this example' code for more details of the restructuring applied againthis revision runs the same as our original site download and upload scriptssee its self-test code at the end for usage detailsand pass in command-line argument to specify "downloador "upload we haven' changed what it doeswe've refactored it for maintainability and reusec:\pp \internet\ftp\mirrorftptools py download test clean target dir firstpassword for lutz on home rmi netconnecting downloading -longmont-classes html to test\ -longmont-classes html as text lines omitted downloading relo-feb -index html to test\relo-feb -index html as text done files downloaded :\pp \internet\ftp\mirrorftptools py upload test clean target dir firstpassword for lutz on learning-python comconnecting uploading test\ -longmont-classes html to -longmont-classes html as text lines omitted uploading test\zopeoutline htm to zopeoutline htm as text done files uploaded although this file can still be run as command-line script like thisits class is really now package of ftp tools that can be mixed into other programs and reused by wrapping its code in classit can be easily customized by redefining its methods--its configuration callssuch as getlocaldirfor examplemay be redefined in subclasses for custom scenarios perhaps most importantlyusing classes optimizes code reusability clients of this file can both upload and download directories by simply subclassing or embedding an instance of this class and calling its methods to see one example of howlet' move on to the next section transferring directory trees with ftplib perhaps the biggest limitation of the website download and upload scripts we just met is that they assume the site directory is flat (hence their namesthat isthe preceding scripts transfer simple files onlyand none of them handle nested subdirectories within the web directory to be transferred client-side scripting
5,460
keep things simpleand store my book support home website as simple directory of files for other sitesthoughincluding one keep at another machinesite transfer scripts are easier to use if they also automatically transfer subdirectories along the way uploading local trees it turns out that supporting directories on uploads is fairly simple--we need to add only bit of recursion and remote directory creation calls the upload script in example - extends the class-based version we just saw in example - to handle uploading all subdirectories nested within the transferred directory furthermoreit recursively transfers subdirectories within subdirectories--the entire directory tree contained within the top-level transfer directory is uploaded to the target directory at the remote server in terms of its code structureexample - is just customization of the ftptools class of the prior section--reallywe're just adding method for recursive uploadsby subclassing as one consequencewe get tools such as parameter configurationcontent type testingand connection and upload code for free herewith oopsome of the work is done before we start example - pp \internet\ftp\mirror\uploadall py #!/bin/env python ""###########################################################################extend the ftptools class to upload all files and subdirectories from local dir tree to remote site/dirsupports nested dirs toobut not the cleanall option (that requires parsing ftp listings to detect remote dirssee cleanall py)to upload subdirectoriesuses os path isdir(pathto see if local file is really directoryftp(mkd(pathto make dirs on the remote machine (wrapped in try in case it already exists there)and recursion to upload all files/dirs inside the nested subdirectory ###########################################################################""import osftptools class uploadall(ftptools ftptools)""upload an entire tree of subdirectories assumes top remote directory exists ""def __init__(self)self fcount self dcount def getcleanall(self)return false don' even ask def uploaddir(selflocaldir)""transferring directory trees with ftplib
5,461
upload simple filesrecur into subdirectories ""localfiles os listdir(localdirfor localname in localfileslocalpath os path join(localdirlocalnameprint('uploading'localpath'to'localnameend='if not os path isdir(localpath)self uploadone(localnamelocalpathlocalnameself fcount + elsetryself connection mkd(localnameprint('directory created'exceptprint('directory not created'self connection cwd(localnamechange remote dir self uploaddir(localpathupload local subdir self connection cwd('change back up self dcount + print('directory exited'if __name__ ='__main__'ftp uploadall(ftp configtransfer(site='learning-python com'rdir='training'user='lutz'ftp run(transferact lambdaftp uploaddir(ftp localdir)print('done:'ftp fcount'files and'ftp dcount'directories uploaded 'like the flat upload scriptthis one can be run on any machine with python and sockets and upload to any machine running an ftp serveri run it both on my laptop pc and on other servers by telnet or ssh to upload sites to my isp the crux of the matter in this script is the os path isdir test near the topif this test detects directory in the current local directorywe create an identically named directory on the remote machine with connection mkd and descend into it with connection cwdand recur into the subdirectory on the local machine (we have to use recursive calls herebecause the shape and depth of the tree are arbitrarylike all ftp object methodsmkd and cwd methods issue ftp commands to the remote server when we exit local subdirectorywe run remote cwd('to climb to the remote parent directory and continuethe recursive call level' return restores the prior directory on the local machine the rest of the script is roughly the same as the original in the interest of spacei'll leave studying this variant in more depth as suggested exercise for more contexttry changing this script so as not to assume that the toplevel remote directory already exists as usual in softwarethere are variety of implementation and operation options here here is the sort of output displayed on the console when the upload-all script is runuploading site with multiple subdirectory levels which maintain with site builder tools it' similar to the flat upload (which you might expectgiven that it is reusing client-side scripting
5,462
subdirectories along the wayc:\pp \internet\ftp\mirroruploadall py website-training password for lutz on learning-python comconnecting uploading website-training\ -public-classes htm to -public-classes htm text uploading website-training\ -public-classes html to -public-classes html text uploading website-training\about html to about html text uploading website-training\books to books directory created uploading website-training\books\index htm to index htm text uploading website-training\books\index html to index html text uploading website-training\books\_vti_cnf to _vti_cnf directory created uploading website-training\books\_vti_cnf\index htm to index htm text uploading website-training\books\_vti_cnf\index html to index html text directory exited directory exited uploading website-training\calendar html to calendar html text uploading website-training\contacts html to contacts html text uploading website-training\estes-nov htm to estes-nov htm text uploading website-training\formalbio html to formalbio html text uploading website-training\fulloutline html to fulloutline html text lines omitted uploading website-training\_vti_pvt\writeto cnf to writeto cnf uploading website-training\_vti_pvt\_vti_cnf to _vti_cnf directory created uploading website-training\_vti_pvt\_vti_cnf\_x_todo htm to _x_todo htm text uploading website-training\_vti_pvt\_vti_cnf\_x_todoh htm to _x_todoh htm text directory exited uploading website-training\_vti_pvt\_x_todo htm to _x_todo htm text uploading website-training\_vti_pvt\_x_todoh htm to _x_todoh htm text directory exited done files and directories uploaded as isthe script of example - handles only directory tree uploadsrecursive uploads are generally more useful than recursive downloads if you maintain your websites on your local pc and upload to server periodicallyas do to also download (mirrora website that has subdirectoriesa script must parse the output of remote listing command to detect remote directories for the same reasonthe recursive upload script was not coded to support the remote directory tree cleanup option of the original--such feature would require parsing remote listings as well the next section shows how deleting remote trees one last example of code reuse at workwhen initially tested the prior section' upload-all scriptit contained bug that caused it to fall into an infinite recursion loopand keep copying the full site into new subdirectoriesover and overuntil the ftp server kicked me off (not an intended feature of the program!in factthe upload got levels deep before being killed by the serverit effectively locked my site until the mess could be repaired transferring directory trees with ftplib
5,463
in an entire remote tree luckilythis was very easy to do given all the reuse that example - inherits from the ftptools superclass herewe just have to define the extension for recursive remote deletions even in tactical mode like thisoop can be decided advantage example - pp \internet\ftp\mirror\cleanall py #!/bin/env python ""#############################################################################extend the ftptools class to delete files and subdirectories from remote directory treesupports nested directories toodepends on the dir(command output formatwhich may vary on some serverssee python' tools\scripts\ftpmirror py for hintsextend me for remote tree downloads#############################################################################""from ftptools import ftptools class cleanall(ftptools)""delete an entire remote tree of subdirectories ""def __init__(self)self fcount self dcount def getlocaldir(self)return none irrelevent here def getcleanall(self)return true implied here def cleandir(self)""for each item in current remote directorydel simple filesrecur into and then del subdirectories the dir(ftp call passes each line to func or method ""lines [each level has own lines self connection dir(lines appendlist current remote dir for line in linesparsed line split(split on whitespace permiss parsed[ assume 'drw filenamefname parsed[- if fname in ('')some include cwd and parent continue elif permiss[ !' 'simple filedelete print('file'fnameself connection delete(fnameself fcount + elsedirectoryrecurdel print('directory'fname client-side scripting
5,464
self cleandir(self connection cwd('self connection rmd(fnameself dcount + print('directory exited'chdir into remote dir clean subdirectory chdir remote back up delete empty remote dir if __name__ ='__main__'ftp cleanall(ftp configtransfer(site='learning-python com'rdir='training'user='lutz'ftp run(cleantarget=ftp cleandirprint('done:'ftp fcount'files and'ftp dcount'directories cleaned 'besides again being recursive in order to handle arbitrarily shaped treesthe main trick employed here is to parse the output of remote directory listing the ftp nlst call used earlier gives us simple list of filenamesherewe use dir to also get file detail lines like thesec:\pp \internet\ftpftp learning-python com ftpcd training ftpdir drwxr-xr- may : drwx--- - may : -rw---- - may : -public-classes htm -rw---- - may : -public-classes html drwx--- - may : books -rw---- - may : calendar-save-aug html -rw---- - may : calendar html drwx--- - may : images -rw---- - may : index html lines omitted this output format is potentially server-specificso check this on your own server before relying on this script for this unix ispif the first character of the first item on the line is character " "the filename at the end of the line names remote directory to parsethe script simply splits on whitespace to extract parts of line notice how this scriptlike others before itmust skip the symbolic and current and parent directory names in listings to work properly for this server oddly this can vary per server as wellone of the servers used for this book' examplesfor instancedoes not include these special names in listings we can verify by running ftplib at the interactive promptas though it were portable ftp client interfacec:\pp \internet\ftppython from ftplib import ftp ftp('ftp rmi net' login('lutz''xxxxxxxx'for in nlst()[: ]print( -longmont-classes html -longmont-classes html -longmont-classes html output lines omitted no or in listings [transferring directory trees with ftplib
5,465
for in [: ]print( -rw- -- - ftp ftp -rw- -- - ftp ftp -rw- -- - ftp ftp ditto for detailed list mar mar jul -longmont-classes html -longmont-classes html -longmont-classes html on the other handthe server ' using in this section does include the special dot namesto be robustour scripts must skip over these names in remote directory listings just in case they're run against server that includes them (herethe test is required to avoid falling into an infinite recursive loop!we don' need to care about local directory listings because python' os listdir never includes or in its resultbut things are not quite so consistent in the "wild westthat is the internet todayf ftp('learning-python com' login('lutz''xxxxxxxx'for in nlst()[: ]print(xhcc thumbs -public-classes htm -public-classes html [ dir( appendfor in [: ]print(xdrwx--- - drwx--- - drwx -rw---- - -rw---- - output lines omitted includes and here ditto for detailed list may : may : feb : hcc thumbs may : -public-classes htm may : -public-classes html the output of our clean-all script in action followsit shows up in the system console window where the script is run you might be able to achieve the same effect with "rm -rfunix shell command in ssh or telnet window on some serversbut the python script runs on the client and requires no other remote access than basic ftp on the clientc:\pp \internet\ftp\mirrorcleanall py password for lutz on learning-python comconnecting file -public-classes htm file -public-classes html file learning-python-interview doc file python-registration-form- pdf file pythonpoweredsmall gif directory _derived file -public-classes htm_cmp_deepblue _vbtn gif file -public-classes htm_cmp_deepblue _vbtn_p gif file -public-classes html_cmp_deepblue _vbtn_p gif file -public-classes html_cmp_deepblue _vbtn gif directory _vti_cnf client-side scripting
5,466
file -public-classes htm_cmp_deepblue _vbtn_p gif file -public-classes html_cmp_deepblue _vbtn_p gif file -public-classes html_cmp_deepblue _vbtn gif directory exited directory exited lines omitted file priorclients html file public_classes htm file python_conf_ora gif file topics html done files and directories cleaned downloading remote trees it is possible to extend this remote tree-cleaner to also download remote tree with subdirectoriesrather than deletingas you walk the remote tree simply create local directory to match remote oneand download nondirectory files we'll leave this final step as suggested exercisethoughpartly because its dependence on the format produced by server directory listings makes it complex to be robust and partly because this use case is less common for me--in practicei am more likely to maintain site on my pc and upload to the server than to download tree if you do wish to experiment with recursive downloadthoughbe sure to consult the script tools\scripts\ftpmirror py in python' install or source tree for hints that script attempts to download remote directory tree by ftpand allows for various directory listing formats which we'll skip here in the interest of space for our purposesit' time to move on to the next protocol on our tour--internet email processing internet email some of the other most commonhigher-level internet protocols have to do with reading and sending email messagespop and imap for fetching email from serverssmtp for sending new messagesand other formalisms such as rfc for specifying email message content and format you don' normally need to know about such acronyms when using common email toolsbut internallyprograms like microsoft outlook and webmail systems generally talk to pop and smtp servers to do your bidding like ftpemail ultimately consists of formatted commands and byte streams shipped over sockets and ports (port for pop for smtpregardless of the nature of its content and attachmentsan email message is little more than string of bytes sent and received through sockets but also like ftppython has standard library modules to simplify all aspects of email processingprocessing internet email
5,467
smtplib for sending email the email module package for parsing email and constructing email these modules are relatedfor nontrivial messageswe typically use email to parse mail text which has been fetched with poplib and use email to compose mail text to be sent with smtplib the email package also handles tasks such as address parsingdate and time formattingattachment formatting and extractionand encoding and decoding of email content ( ,guuencodebase additional modules handle more specific tasks ( mimetypes to map filenames to and from content typesin the next few sectionswe explore the pop and smtp interfaces for fetching and sending email from and to serversand the email package interfaces for parsing and composing email message text other email interfaces in python are analogous and are documented in the python library reference manual ss unicode in python and email tools in the prior sections of this we studied how unicode encodings can impact scripts using python' ftplib ftp tools in some depthbecause it illustrates the implications of python ' unicode string model for real-world programming in shortall binary mode transfers should open local output and input files in binary mode (modes wb and rbtext-mode downloads should open local output files in text mode with explicit encoding names (mode wwith an encoding argument that defaults to latin within ftplib itselftext-mode uploads should open local input files in binary mode (mode rbthe prior sections describe why these rules are in force the last two points here differ for scripts written originally for python as you might expectgiven that the underlying sockets transfer byte strings todaythe email story is somewhat convoluted for unicode in python as well as brief previewfetching the poplib module returns fetched email text in bytes string form command text sent to the server is encoded per utf internallybut replies are returned as raw binary bytes and not decoded into str text ss imapor internet message access protocolwas designed as an alternative to popbut it is still not as widely available todayand so it is not presented in this text for instancemajor commercial providers used for this book' examples provide only pop (or web-basedaccess to email see the python library manual for imap server interface details python used to have rfc module as wellbut it' been subsumed by the email package in client-side scripting
5,468
the smtplib module accepts email content to send as str strings internallymessage text passed in str form is encoded to binary bytes for transmission using the ascii encoding scheme passing an already encoded bytes string to the send call may allow more explicit control composing the email package produces unicode str strings containing plain text when generating full email text for sending with smtplib and accepts optional encoding specifications for messages and their partswhich it applies according to email standard rules message headers may also be encoded per emailmimeand unicode conventions parsing the email package in currently requires raw email byte strings of the type fetched with poplib to be decoded into unicode str strings as appropriate before it can be passed in to be parsed into message object this pre-parse decoding might be done by defaultuser preferencemail headers inspectionor intelligent guess because this requirement raises difficult issues for package clientsit may be dropped in future version of email and python navigating the email package returns most message components as str stringsthough parts content decoded by base and other email encoding schemes may be returned as bytes stringsparts fetched without such decoding may be str or bytesand some str string parts are internally encoded to bytes with scheme raw-unicode-escape before processing message headers may be decoded by the package on request as well if you're migrating email scripts (or your mindsetfrom xyou'll need to treat email text fetched from server as byte stringsand encode it before passing it along for parsingscripts that send or compose email are generally unaffected (and this may be the majority of python email-aware scripts)though content may have to be treated specially if it may be returned as byte strings this is the story in python which is of course prone to change over time we'll see how these email constraints translate into code as we move along in this section suffice it to saythe text on the internet is not as simple as it used to bethough it probably shouldn' have been anyhow popfetching email confessup until just before took lowest-common-denominator approach to email preferred to check my messages by telnetting to my isp and using simple command-line email interface of coursethat' not ideal for mail with attachmentspicturesand the likebut its portability was staggering--because telnet runs on almost popfetching email
5,469
anywhere on the planet given that make my living traveling around the world teaching python classesthis wild accessibility was big win as with website maintenancetimes have changed on this front somewhere along the waymost isps began offering web-based email access with similar portability and dropped telnet altogether when my isp took away telnet accesshoweverthey also took away one of my main email access methods luckilypython came to the rescue again--by writing email access scripts in pythoni could still read and send email from any machine in the world that has python and an internet connection python can be as portable solution as telnetbut much more powerful moreoveri can still use these scripts as an alternative to tools suggested by the isp besides my not being fond of delegating control to commercial products of large companiesclosed email tools impose choices on users that are not always ideal and may sometimes fail altogether in many waysthe motivation for coding python email scripts is the same as it was for the larger guis in the scriptability of python programs can be decided advantage for examplemicrosoft outlook historically and by default has preferred to download mail to your pc and delete it from the mail server as soon as you access it this keeps your email box small (and your isp happy)but it isn' exactly friendly to people who travel and use multiple machines along the way--once accessedyou cannot get to prior email from any machine except the one to which it was initially downloaded worsethe web-based email interfaces offered by my isps have at times gone offline completelyleaving me cut off from email (and usually at the worst possible timethe next two scripts represent one first-cut solution to such portability and reliability constraints (we'll see others in this and later the firstpopmail pyis simple mail reader toolwhich downloads and prints the contents of each email in an email account this script is admittedly primitivebut it lets you read your email on any machine with python and socketsmoreoverit leaves your email intact on the serverand isn' susceptible to webmail outages the secondsmtpmail pyis one-shot script for writing and sending new email message that is as portable as python itself later in this we'll implement an interactive console-based email client (pymail)and later in this book we'll code full-blown gui email tool (pymailguiand web-based email program of our own (pymailcgifor nowwe'll start with the basics mail configuration module before we get to the scriptslet' first take look at common module they import and use the module in example - is used to configure email parameters appropriately for particular user it' simply collection of assignments to variables used by mail programs that appear in this bookeach major mail client has its own versionto allow client-side scripting
5,470
easy to configure the book' email programs for particular userwithout having to edit actual program logic code if you want to use any of this book' email programs to do mail processing of your ownbe sure to change its assignments to reflect your serversaccount usernamesand so on (as shownthey refer to email accounts used for developing this booknot all scripts use all of these settingswe'll revisit this module in later examples to explain more of them note that some isps may require that you be connected directly to their systems in order to use their smtp servers to send mail for examplewhen connected directly by dial-up in the pasti could use my isp' server directlybut when connected via broadbandi had to route requests through cable internet provider you may need to adjust these settings to match your configurationsee your isp to obtain the required pop and smtp servers alsosome smtp servers check domain name validity in addressesand may require an authenticating login step--see the smtp section later in this for interface details example - pp \internet\email\mailconfig py ""user configuration settings for various email programs (pymail/mailtools version)email scripts get their server names and other email config options from this modulechange me to reflect your server names and mail preferences""#(required for loaddeleteallpop email server machineuser #popservername 'pop secureserver netpopusername 'pp @learning-python com#(required for sendallsmtp email server machine name see python smtpd module for smtp server class to run locally#smtpservername 'smtpout secureserver net#(optionalallpersonal information used by clients to fill in mail if setsignature -can be triple-quoted blockignored if empty stringaddress -used for initial value of "fromfield if not emptyno longer tries to guess from for repliesthis had varying success#myaddress 'pp @learning-python commysignature ('thanks,\ '--mark lutz (popfetching email
5,471
authenticatedset user to none or 'if no login/authentication is requiredset pswd to name of file holding your smtp passwordor an empty string to force programs to ask (in consoleor gui)#smtpuser none smtppasswdfile 'per your isp set to 'to be asked #(optionalmailtoolsname of local one-line text file with your pop passwordif empty or file cannot be readpswd is requested when first connectingpswd not encryptedleave this empty on shared machines#poppasswdfile ' :\temp\pymailgui txtset to 'to be asked #(requiredmailtoolslocal file where sent messages are saved by some clients#sentmailfile \sentmail txtmeans in current working dir #(requiredpymailpymail local file where pymail saves pop mail on request#savemailfile ' :\temp\savemail txtnot used in pymailguidialog #(requiredpymailmailtoolsfetchencoding is the unicode encoding used to decode fetched full message bytesand to encode and decode message text if stored in text-mode save filessee for detailsthis is limited and temporary approach to unicode encodings until new bytes-friendly email package is developedheadersencodeto is for sent headerssee #fetchencoding 'utf headersencodeto none ehow to decode and store message text (or latin ? ehow to encode non-ascii headers sent (none=utf #(optionalmailtoolsthe maximum number of mail headers or messages to download on each load requestgiven this setting nmailtools fetches at most of the most recently arrived mailsolder mails outside this set are not fetched from the serverbut are returned as empty/dummy emailsif this is assigned to none (or )loads will have no such limituse this if you have very many mails in your inboxand your internet or mail server speed makes full loads too slow to be practicalsome clients also load only newly-arrived emailsbut this setting is independent of that feature#fetchlimit emaximum number headers/emails to fetch on loads client-side scripting
5,472
on to reading email in pythonthe script in example - employs python' standard poplib modulean implementation of the client-side interface to pop--the post office protocol pop is well-defined and widely available way to fetch email from servers over sockets this script connects to pop server to implement simple yet portable email download and display tool example - pp \internet\email\popmail py #!/usr/local/bin/python ""#############################################################################use the python pop mail interface module to view your pop email account messagesthis is just simple listing--see pymail py for client with more user interaction featuresand smtpmail py for script which sends mailpop is used to retrieve mailand runs on socket using port number on the server machinebut python' poplib hides all protocol detailsto send mailuse the smtplib module (or os popen('mail ')see alsoimaplib module for imap alternativepymailgui/pymailcgi for more features#############################################################################""import poplibgetpasssysmailconfig mailserver mailconfig popservername ex'pop rmi netmailuser mailconfig popusername ex'lutzmailpasswd getpass getpass('password for % ?mailserverprint('connecting 'server poplib pop (mailserverserver user(mailuserserver pass_(mailpasswdconnectlog in to mail server pass is reserved word tryprint(server getwelcome()print returned greeting message msgcountmsgbytes server stat(print('there are'msgcount'mail messages in'msgbytes'bytes'print(server list()print('- input('[press enter key]'for in range(msgcount)hdrmessageoctets server retr( + for line in messageprint(line decode()print('- if msgcount input('[press enter key]'finallyserver quit(print('bye 'octets is byte count retrieveprint all mail mail text is bytes in mail box locked till quit make sure we unlock mbox else locked till timeout popfetching email
5,473
lib pop objectpassing in the email server machine' name as stringserver poplib pop (mailserverif this call doesn' raise an exceptionwe're connected (by socketto the pop server listening on pop port number at the machine where our email account lives the next thing we need to do before fetching messages is tell the server our username and passwordnotice that the password method is called pass_ without the trailing underscorepass would name reserved word and trigger syntax errorserver user(mailuserserver pass_(mailpasswdconnectlog in to mail server pass is reserved word to keep things simple and relatively securethis script always asks for the account password interactivelythe getpass module we met in the ftp section of this is used to input but not display password string typed by the user once we've told the server our username and passwordwe're free to fetch mailbox information with the stat method (number messagestotal bytes among all messagesand fetch the full text of particular message with the retr method (pass the message number--they start at the full text includes all headersfollowed by blank linefollowed by the mail' text and any attached parts the retr call sends back tuple that includes list of line strings representing the content of the mailmsgcountmsgbytes server stat(hdrmessageoctets server retr( + octets is byte count we close the email server connection by calling the pop object' quit methodserver quit(else locked till timeout notice that this call appears inside the finally clause of try statement that wraps the bulk of the script to minimize complications associated with changespop servers lock your email inbox between the time you first connect and the time you close your connection (or until an arbitrarysystem-defined timeout expiresbecause the pop quit method also unlocks the mailboxit' crucial that we do this before exitingwhether an exception is raised during email processing or not by wrapping the action in try/finally statementwe guarantee that the script calls quit on exit to unlock the mailbox to make it accessible to other processes ( delivery of incoming emailfetching messages here is the popmail script of example - in actiondisplaying two messages in my account' mailbox on machine pop secureserver net--the domain name of the mail server machine used by the isp hosting my learning-python com domain nameas configured in the module mailconfig to keep this output reasonably sizedi've omitted or truncated few irrelevant message header lines hereincluding most of the client-side scripting
5,474
gory details of raw email textc:\pp \internet\emailpopmail py password for pop secureserver netconnecting '+ok there are mail messages in bytes ( '+ok '[ ' ' ' '] [press enter keyreceived(qmail invoked from network) may : : - -ironport-anti-spam-resultaskcag uvrvllalgdsb jhbacdf fjckvaqebaqklcakraxreceivedfrom by webmail earthlink net with httpwed may message-id< javamail root@mswamui-thinleaf atl sa earthl datewed may : : - (edtfromlutz@rmi net reply-tolutz@rmi net topp @learning-python com subjecti' lumberjackand ' okay mime-version content-typetext/plaincharset=utf- content-transfer-encoding bit -mailerearthlink zoo mail -elnk-trace cab bca da af cf edc -originating-ip -nonspamnone cut down treesi skip and jumpi like to press wild flowers [press enter keyreceived(qmail invoked from network) may : : - -ironport-anti-spam-resultalibaiss uthsoc mwdsb jhbacdf fjd baqebaqyncgcriq received(qmail invoked by uid ) may : : - content-transfer-encodingquoted-printable content-typetext/plaincharset="utf- -originating-ip user-agentweb-based email message-id< deec fd acfef cad wbe@emai fromlutz@learning-python com topp @learning-python com cclutz@learning-python com subjecttesting datewed may : : - mime-version -nonspamnone testing python mail tools bye popfetching email
5,475
prints the complete and raw full text of one message at timepausing between each until you press the enter key the input built-in is called to wait for the key press between message displays the pause keeps messages from scrolling off the screen too fastto make them visually distinctemails are also separated by lines of dashes we could make the display fancier ( we can use the email package to parse headersbodiesand attachments--watch for examples in this and later )but here we simply display the whole message that was sent this works well for simple mails like these twobut it can be inconvenient for larger messages with attachmentswe'll improve on this in later clients this book won' cover the full of set of headers that may appear in emailsbut we'll make use of some along the way for examplethe -mailer header lineif presenttypically identifies the sending programwe'll use it later to identify python-coded email senders we write the more common headers such as from and subject are more crucial to message in facta variety of extra header lines can be sent in message' text the received headersfor exampletrace the machines that message passed through on its way to the target mailbox because popmail prints the entire raw text of messageyou see all headers herebut you usually see only few by default in end-user-oriented mail guis such as outlook and webmail pages the raw text here also makes apparent the email structure we noted earlieran email in general consists of set of headers like those herefollowed by blank linewhich is followed by the mail' main textthough as we'll see laterthey can be more complex if there are alternative parts or attachments the script in example - never deletes mail from the server mail is simply retrieved and printed and will be shown again the next time you run the script (barring deletion in another toolof courseto really remove mail permanentlywe need to call other methods ( server dele(msgnum))but such capability is best deferred until we develop more interactive mail tools notice how the reader script decodes each mail content line with line decode into str string for displayas mentioned earlierpoplib returns content as bytes strings in in factif we change the script to not decodethis becomes more obvious in its output[press enter keyassorted lines omitted 'datewed may : : - (edt) 'fromlutz@rmi netb'reply-tolutz@rmi netb'topp @learning-python comb"subjecti' lumberjackand ' okayb'mime-version 'content-typetext/plaincharset=utf- 'content-transfer-encoding bitb' -mailerearthlink zoo mail client-side scripting
5,476
' cut down treesi skip and jump, ' like to press wild flowers 'as we'll see laterwe'll need to decode similarly in order to parse this text with email tools the next section exposes the bytes-based interface as well fetching email at the interactive prompt if you don' mind typing code and reading pop server messagesit' possible to use the python interactive prompt as simple email clienttoo the following session uses two additional interfaces we'll apply in later examplesconn list(returns list of "message-number message-sizestrings conn topn retrieves just the header text portion of message number the top call also returns tuple that includes the list of line strings sent backits second argument tells the server how many additional lines after the headers to sendif any if all you need are header detailstop can be much quicker than the full text fetch of retrprovided your mail server implements the top command (most do) :\pp \internet\emailpython from poplib import pop conn pop ('pop secureserver net'conn user('pp @learning-python com' '+ok conn pass_('xxxxxxxx' '+ok connect to server log in to account conn stat(num mailsnum bytes ( conn list(( '+ok '[ ' ' ' '] conn top( ( '+ok octets '[ 'received(qmail invoked from network) may lines omitted ' -originating-ip ' ' -nonspamnone' '' ''] conn retr( ( '+ok octets '[ 'received(qmail invoked from network) may lines omitted ' -originating-ip ' ' -nonspamnone' '' ' cut down treesi skip and jump,' ' like to press wild flowers ' '' ''] conn quit( '+ok popfetching email
5,477
simply decode each line to normal string as it is printedlike our pop mail script didor concatenate the line strings returned by retr or top adding newline betweenany of the following will suffice for an open pop server objectinfomsgoct connection retr( fetch first email in mailbox for in msgprint( decode()four ways to display message lines print( '\njoin(msgdecode() [print( decode()for in msgx list(map(printmap(bytes decodemsg))parsing email text to extract headers and components is more complexespecially for mails with attached and possibly encoded partssuch as images as we'll see later in this the standard library' email package can parse the mail' full or headers text after it has been fetched with poplib (or imaplibsee the python library manual for details on other pop module tools as of python there is also pop _ssl class in the poplib module that connects to the server over an ssl-encrypted socket on port by default (the standard port for pop over sslit provides an identical interfacebut it uses secure sockets for the conversation where supported by servers smtpsending email there is proverb in hackerdom that states that every useful computer program eventually grows complex enough to send email whether such wisdom rings true or not in practicethe ability to automatically initiate email from within program is powerful tool for instancetest systems can automatically email failure reportsuser interface programs can ship purchase orders to suppliers by emailand so on moreovera portable python mail script could be used to send messages from any computer in the world with python and an internet connection that supports standard email protocols freedom from dependence on mail programs like outlook is an attractive feature if you happen to make your living traveling around teaching python on all sorts of computers luckilysending email from within python script is just as easy as reading it in factthere are at least four ways to do socalling os popen to launch command-line mail program on some systemsyou can send email from script with call of the formos popen('mail - "xxxa@ '' 'write(textas we saw earlier in the bookthe popen tool runs the command-line string passed to its first argumentand returns file-like object connected to it if we use an open mode of wwe are connected to the command' standard input stream--herewe write the text of the new mail message to the standard unix mail command-line client-side scripting
5,478
running python script running the sendmail program the open source sendmail program offers another way to initiate mail from program assuming it is installed and configured on your systemyou can launch it using python tools like the os popen call of the previous paragraph using the standard smtplib python module python' standard library comes with support for the client-side interface to smtp--the simple mail transfer protocol-- higher-level internet standard for sending mail over sockets like the poplib module we met in the previous sectionsmtplib hides all the socket and protocol details and can be used to send mail on any machine with python and suitable socket-based internet link fetching and using third-party packages and tools other tools in the open source library provide higher-level mail handling packages for pythonmost build upon one of the prior three techniques of these four optionssmtplib is by far the most portable and direct using os popen to spawn mail program usually works on unix-like platforms onlynot on windows (it assumes command-line mail program)and requires spawning one or more processes along the way and although the sendmail program is powerfulit is also somewhat unix-biasedcomplexand may not be installed even on all unix-like machines by contrastthe smtplib module works on any machine that has python and an internet link that supports smtp accessincluding unixlinuxmacand windows it sends mail over sockets in-processinstead of starting other programs to do the work moreoversmtp affords us much control over the formatting and routing of email smtp mail sender script since smtp is arguably the best option for sending mail from python scriptlet' explore simple mailing program that illustrates its interfaces the python script shown in example - is intended to be used from an interactive command lineit reads new mail message from the user and sends the new mail by smtp using python' smtplib module example - pp \internet\email\smtpmail py #!/usr/local/bin/python ""##########################################################################use the python smtp mail interface module to send email messagesthis is just simple one-shot send script--see pymailpymailguiand pymailcgi for clients with more user interaction featuresalso see popmail py for script that retrieves mailand the mailtools pkg for attachments and formatting with the standard library email package##########################################################################""smtpsending email
5,479
mailserver mailconfig smtpservername from input('from'strip(to input('to'strip(tos to split(';'subj input('subj'strip(date email utils formatdate(exsmtp rmi net or import from mailconfig expython-list@python org allow list of recipients curr datetimerfc standard headersfollowed by blank linefollowed by text text ('from% \nto% \ndate% \nsubject% \ \ (fromtodatesubj)print('type message textend with line=[ctrl+ (unix)ctrl+ (windows)]'while trueline sys stdin readline(if not linebreak exit on ctrl- / #if line[: ='from'line '>line servers may escape text +line print('connecting 'server smtplib smtp(mailserverfailed server sendmail(fromtostextserver quit(if failedprint('failed recipients:'failedelseprint('no errors 'print('bye 'connectno log-in step smtplib may raise exceptions toobut let them pass here most of this script is user interface--it inputs the sender' address (from)one or more recipient addresses (toseparated by ";if more than one)and subject line the sending date is picked up from python' standard time modulestandard header lines are formattedand the while loop reads message lines until the user types the end-offile character (ctrl- on windowsctrl- on linuxto be robustbe sure to add blank line between the header lines and the body in the message' textit' required by the smtp protocol and some smtp servers enforce this our script conforms by inserting an empty line with \ \ at the end of the string format expression--one \ to terminate the current line and another for blank linesmtplib expands \ to internet-style \ \ internally prior to transmissionso the short form is fine here later in this we'll format our messages with the python email packagewhich handles such details for us automatically the rest of the script is where all the smtp magic occursto send mail by smtpsimply run these two sorts of callsserver smtplib smtp(mailservermake an instance of the smtp objectpassing in the name of the smtp server that will dispatch the message first if this doesn' throw an exceptionyou're connected client-side scripting
5,480
method establishes connection to serverbut the smtp object calls this method automatically if the mail server name is passed in this way failed server sendmail(fromtostextcall the smtp object' sendmail methodpassing in the sender addressone or more recipient addressesand the raw text of the message itself with as many standard mail header lines as you care to provide when you're donebe sure to call the object' quit method to disconnect from the server and finalize the transaction notice thaton failurethe sendmail method may either raise an exception or return list of the recipient addresses that failedthe script handles the latter case itself but lets exceptions kill the script with python error message subtlycalling the server object' quit method after sendmail raises an exception may or may not work as expected--quit can actually hang until server timeout if the send fails internally and leaves the interface in an unexpected state for instancethis can occur on unicode encoding errors when translating the outgoing mail to bytes per the ascii scheme (the rset reset request hangs in this casetooan alternative close method simply closes the client' sockets without attempting to send quit command to the serverquit calls close internally as last step (assuming the quit command can be sent!for advanced usagesmtp objects provide additional calls not used in this exampleserver login(userpasswordprovides an interface to smtp servers that require and support authenticationwatch for this call to appear as an option in the mail tools package example later in this server starttls([keyfile[certfile]]puts the smtp connection in transport layer security (tlsmodeall commands will be encrypted using the python ssl module' socket wrapper ssl supportand they assume the server supports this mode see the python library manual for more on these and other calls not covered here sending messages let' ship few messages across the world the smtpmail script is one-shot tooleach run allows you to send single new mail message like most of the client-side tools in this it can be run from any computer with python and an internet link that supports smtp (most dothough some public access machines may restrict users to http [webaccess only or require special server smtp configurationhere it is running on windowsc:\pp \internet\emailsmtpmail py fromeric the half bee@yahoo com topp @learning-python com smtpsending email
5,481
type message textend with line=[ctrl+ (unix)ctrl+ (windows)fiddle de dumfiddle de deeeric the half bee ^ connecting no errors bye this mail is sent to the book' email account address (pp @learning-python com)so it ultimately shows up in the inbox at my ispbut only after being routed through an arbitrary number of machines on the netand across arbitrarily distant network links it' complex at the bottombut usuallythe internet "just works notice the from addressthough--it' completely fictitious (as far as knowat leastit turns out that we can usually provide any from address we like because smtp doesn' check its validity (only its general format is checkedfurthermoreunlike popthere is usually no notion of username or password in smtpso the sender is more difficult to determine we need only pass email to any machine with server listening on the smtp portand we don' need an account or login on that machine herethe name eric the half bee@yahoo com works just fine as the sendermarketing geek from hell@spam com might work just as well in facti didn' import from email address from the mailconfig py module on purposebecause wanted to be able to demonstrate this behaviorit' the basis of some of those annoying junk emails that show up in your mailbox without real sender' address |marketers infected with -millionaire mania will email advertising to all addresses on list without providing real from addressto cover their tracks normallyof courseyou should use the same to address in the message and the smtp call and provide your real email address as the from value (that' the only way people will be able to reply to your messagemoreoverapart from teasing your significant othersending phony addresses is often just plain bad internet citizenship let' run the script again to ship off another mail with more politically correct coordinatesc:\pp \internet\emailsmtpmail py frompp @learning-python com topp @learning-python com subjtesting smtpmail type message textend with line=[ctrl+ (unix)ctrl+ (windows)lovely spamwonderful spam^ connecting no errors bye |we all know by now that such junk mail is usually referred to as spambut not everyone knows that this name is reference to monty python skit in which restaurant' customers find it difficult to hear the reading of menu options over group of vikings singing an increasingly loud chorus of "spamspamspam hence the tie-in to junk email spam is used in python program examples as sort of generic variable namethough it also pays homage to the skit client-side scripting
5,482
at this pointwe could run whatever email tool we normally use to access our mailbox to verify the results of these two send operationsthe two new emails should show up in our mailbox regardless of which mail client is used to view them since we've already written python script for reading mailthoughlet' put it to use as verification tool--running the popmail script from the last section reveals our two new messages at the end of the mail list (again parts of the output have been trimmed to conserve space and protect the innocent here) :\pp \internet\emailpopmail py password for pop secureserver netconnecting '+ok there are mail messages in bytes ( '+ok '[ ' ' ' ' ' ' ' '] [press enter keyfirst two mails omitted received(qmail invoked from network) may : : - receivedfrom unknown (helo pismtp - prod phx secureserver net((envelope-sender by plsmtp - prod phx secureserver net (qmail- with smtp for may : : - more deleted receivedfrom by smtp mailmt com (argosoft mail server net for thu may : : - fromeric the half bee@yahoo com topp @learning-python com datethu may : : - subjecta message-idx-fromip -nonspamnone fiddle de dumfiddle de deeeric the half bee [press enter keyreceived(qmail invoked from network) may : : - receivedfrom unknown (helo pismtp - prod phx secureserver net((envelope-sender by plsmtp - prod phx secureserver net (qmail- with smtp for may : : - more deleted receivedfrom by smtp mailmt com (argosoft mail server net for thu may : : - frompp @learning-python com topp @learning-python com datethu may : : - smtpsending email
5,483
message-idx-fromip -nonspamnone lovely spamwonderful spambye notice how the fields we input to our script show up as headers and text in the email' raw text delivered to the recipient technicallysome isps test to make sure that at least the domain of the email sender' address (the part after "@"is realvalid domain nameand disallow delivery if not as mentioned earliersome servers also require that smtp senders have direct connection to their network and may require an authentication call with username and password (described near the end of the preceding sectionin the second edition of the booki used an isp that let me get away with more nonsensebut this may vary per serverthe rules have tightened since then to limit spam manipulating both from and to the first mail listed at the end of the preceding section was the one we sent with fictitious sender addressthe second was the more legitimate message like sender addressesheader lines are bit arbitrary under smtp our smtpmail script automatically adds from and to header lines in the message' text with the same addresses that are passed to the smtp interfacebut only as polite convention sometimesthoughyou can' tell who mail was sent toeither--to obscure the target audience or to support legitimate email listssenders may manipulate the contents of both these headers in the message' text for exampleif we change smtpmail to not automatically generate "to:header line with the same address(essent to the smtp interface calltext ('from% \ndate% \nsubject% \ (fromdatesubj)we can then manually type "to:header that differs from the address we're really sending to--the "toaddress list passed into the smtplib send call gives the true recipientsbut the "to:header line in the text of the message is what most mail clients will display (see smtpmail-noto py in the examples package for the code needed to support such anonymous behaviorand be sure to type blank line after "to:") :\pp \internet\emailsmtpmail-noto py fromeric the half bee@aol com topp @learning-python com subja type message textend with line=(ctrl or ztonobody in particular@marketing com spamspam and eggsspamspamand spam ^ client-side scripting
5,484
no errors bye in some waysthe from and to addresses in send method calls and message header lines are similar to addresses on envelopes and letters in envelopesrespectively the former is used for routingbut the latter is what the reader sees herefrom is fictitious in both places moreoveri gave the real to address for the account on the serverbut then gave fictitious name in the manually typed "to:header line--the first address is where it really goes and the second appears in mail clients if your mail tool picks out the "to:linesuch mails will look odd when viewed for instancewhen the mail we just sent shows up in my mailbox at learningpython comit' difficult to tell much about its origin or destination in the webmail interface my isp providesas captured in figure - figure - anonymous mail in web-mail client (see also aheadpymailguifurthermorethis email' raw text won' help unless we look closely at the "received:headers added by the machines it has been routed throughc:\pp \internet\emailpopmail py password for pop secureserver netconnecting '+ok there are mail messages in bytes ( '+ok '[ ' ' ' ' ' ' ' ' ' '] smtpsending email
5,485
first three mails omitted received(qmail invoked from network) may : : - receivedfrom unknown (helo pismtp - prod phx secureserver net((envelope-sender by plsmtp - prod phx secureserver net (qmail- with smtp for may : : - more deleted receivedfrom by smtp mailmt com (argosoft mail server net for thu may : : - fromeric the half bee@aol com datethu may : : - subjecta tonobody in particular@marketing com message-idx-fromip -nonspamnone spamspam and eggsspamspamand spam bye once againthoughdon' do this unless you have good cause this demonstration is intended only to help you understand how mail headers factor into email processing to write an automatic spam filter that deletes incoming junk mailfor instanceyou need to know some of the telltale signs to look for in message' text spamming techniques have grown much more sophisticated than simply forging sender and recipient namesof course (you'll find much more on the subject on the web at large and in the spambayes mail filter written in python)but it' one common trick on the other handsuch to address juggling may also be useful in the context of legitimate mailing lists--the name of the list appears in the "to:header when the message is viewednot the potentially many individual recipients named in the send-mail call as the next section' example demonstratesa mail client can simply send mail to all on the list but insert the general list name in the "to:header but in other contextssending email with bogus "from:and "to:lines is equivalent to making anonymous phone calls most mailers won' even let you change the from lineand they don' distinguish between the to address and header line when you program mail scripts of your ownthoughsmtp is wide open in this regard so be good out thereok client-side scripting
5,486
in the prior version of the smtpmail script of example - simple date format was used for the date email header that didn' quite follow the smtp date formatting standardimport time time asctime('wed may : : most servers don' care and will let any sort of date text appear in date header linesor even add one if needed clients are often similarly forgivingbut not alwaysone of my isp webmail programs shows dates correctly anyhowbut another leaves such illformed dates blank in mail displays if you want to be more in line with the standardyou could format the date header with code like this (the result can be parsed with standard tools such as the time strptime call)import time gmt time gmtime(time time()fmt '% % % % % :% :% gmtstr time strftime(fmtgmthdr 'datestr print(hdrthe hdr variable' value looks like this when this code is rundatewed may : : gmt the time strftime call allows arbitrary date and time formattingtime asctime is just one standard format better yetdo what smtpmail does now--in the newer email package (described in this an email utils call can be used to properly format date and time automatically the smtpmail script uses the first of the following format alternativesimport email utils email utils formatdate('wed may : : - email utils formatdate(localtime=true'wed may : : - email utils formatdate(usegmt=true'wed may : : gmtsee the pymail and mailtools examples in this for additional usage examplesthe latter is reused by the larger pymailgui and pymailcgi email clients later in this book sending email at the interactive prompt so where are we in the internet abstraction model nowwith all this email fetching and sending going onit' easy to lose the forest for the trees keep in mind that because mail is transferred over sockets (remember sockets?)they are at the root of all this activity all email read and written ultimately consists of formatted bytes shipped over smtpsending email
5,487
interfaces in python hide all the details moreoverthe scripts we've begun writing even hide the python interfaces and provide higher-level interactive tools both the popmail and smtpmail scripts provide portable email tools but aren' quite what we' expect in terms of usability these days later in this we'll use what we've seen thus far to implement more interactiveconsole-based mail tool in the next we'll also code tkinter email guiand then we'll go on to build web-based interface in later all of these toolsthoughvary primarily in terms of user interface onlyeach ultimately employs the python mail transfer modules we've met here to transfer mail message text over the internet with sockets before we move onone more smtp notejust as for reading mailwe can use the python interactive prompt as our email sending clienttooif we type calls manually the followingfor examplesends message through my isp' smtp server to two recipient addresses assumed to be part of mail listc:\pp \internet\emailpython from smtplib import smtp conn smtp('smtpout secureserver net'conn sendmail'pp @learning-python com'true sender ['lutz@rmi net''pp @learning-python com']true recipients """frompp @learning-python com tomaillist subjecttest interactive smtplib testing """{conn quit(quit(requireddate added ( 'closing connection good bye 'we'll verify receipt of this message in later email client programthe "torecipient shows up as "maillistin email clients-- completely valid use case for header manipulation in factyou can achieve the same effect with the smtpmail-noto script by separating recipient addresses at the "to?prompt with semicolon ( lutz@rmi netpp @learning-python comand typing the email list' name in the "to:header line mail clients that support mailing lists automate such steps sending mail interactively this way is bit tricky to get rightthough--header lines are governed by standardsthe blank line after the subject line is required and significantfor instanceand date is omitted altogether (one is added for usfurthermoremail formatting gets much more complex as we start writing messages with attachments in practicethe email package in the standard library is generally used to construct emailsbefore shipping them off with smtplib the package lets us build mails by assigning headers and attaching and possibly encoding partsand creates correctly formatted mail text to learn howlet' move on to the next section client-side scripting
5,488
the second edition of this book used handful of standard library modules (rfc stringioand moreto parse the contents of messagesand simple text processing to compose them additionallythat edition included section on extracting and decoding attached parts of message using modules such as mhlibmimetoolsand base in the third editionthose tools were still availablebut werefranklya bit clumsy and error-prone parsing attachments from messagesfor examplewas trickyand composing even basic messages was tedious (in factan early printing of the prior edition contained potential bugbecause it omitted one \ character in string formatting operationadding attachments to sent messages wasn' even attempteddue to the complexity of the formatting involved most of these tools are gone completely in python as write this fourth editionpartly because of their complexityand partly because they've been made obsolete luckilythings are much simpler today after the second editionpython sprouted new email package-- powerful collection of tools that automate most of the work behind parsing and composing email messages this module gives us an object-based message interface and handles all the textual message structure detailsboth analyzing and creating it not only does this eliminate whole class of potential bugsit also promotes more advanced mail processing things like attachmentsfor instancebecome accessible to mere mortals (and authors with limited book real estatein factan entire original section on manual attachment parsing and decoding was deleted in the third edition--it' essentially automatic with email the new package parses and constructs headers and attachmentsgenerates correct email textdecodes and encodes base quoted-printableand uuencoded dataand much more we won' cover the email package in its entirety in this bookit is well documented in python' library manual our goal here is to explore some example usage codewhich you can study in conjunction with the manuals but to help get you startedlet' begin with quick overview in nutshellthe email package is based around the message object it providesparsing mail mail' full textfetched from poplib or imaplibis parsed into new message objectwith an api for accessing its components in the objectmail headers become dictionary-like keysand components become "payloadthat can be walked with generator interface (more on payloads in momentcreating mail new mails are composed by creating new message objectusing an api to attach headers and partsand asking the object for its print representation-- correctly formatted mail message textready to be passed to the smtplib module for delivery headers are added by key assignment and attachments by method calls emailparsing and composing mail content
5,489
creating new ones from scratch in both casesemail can automatically handle details like content encodings ( attached binary images can be treated as text with base encoding and decoding)content typesand more message objects since the email module' message object is at the heart of its apiyou need cursory understanding of its form to get started in shortit is designed to reflect the structure of formatted email message each message consists of three main pieces of informationtype content type (plain texthtml textjpeg imageand so on)encoded as mime main type and subtype for instance"text/htmlmeans the main type is text and the subtype is html ( web page)"image/jpegmeans jpeg photo "multipart/mixedtype means there are nested parts within the message headers dictionary-like mapping interfacewith one key per mail header (fromtoand so onthis interface supports almost all of the usual dictionary operationsand headers may be fetched or set by normal key indexing content "payload,which represents the mail' content this can be either string (bytes or strfor simple messagesor list of additional message objects for multipart container messages with attached or alternative parts for some oddball typesthe payload may be python none object the mime type of message is key to understanding its content for examplemails with attached images may have main top-level message (type multipart/mixed)with three more message objects in its payload--one for its main text (type text/plain)followed by two of type image for the photos (type image/jpegthe photo parts may be encoded for transmission as text with base or another schemethe encoding typeas well as the original image filenameare specified in the part' headers similarlymails that include both simple text and an html alternative will have two nested message objects in their payloadof type plain text (text/plainand html text (text/html)along with main root message of type multipart/alternative your mail client decides which part to displayoften based on your preferences simpler messages may have just root message of type text/plain or text/htmlrepresenting the entire message body the payload for such mails is simple string they may also have no explicitly given type at allwhich generally defaults to text/plain some single-part messages are text/htmlwith no text/plain alternative--they require web browser or other html viewer (or very keen-eyed user client-side scripting
5,490
practicesuch as message/delivery status most messages have main text partthough it is not requiredand may be nested in multipart or other construct in all casesan email message is simplelinear stringbut these message structures are automatically detected when mail text is parsed and are created by your method calls when new messages are composed for instancewhen creating messagesthe message attach method adds parts for multipart mailsand set_payload sets the entire payload to string for simple mails message objects also have assorted properties ( the filename of an attachment)and they provide convenient walk generator methodwhich returns the next message in the payload each time through in for loop or other iteration context because the walker yields the root message object first ( self)single-part messages don' have to be handled as special casea nonmultipart message is effectively message with single item in its payload--itself ultimatelythe message object structure closely mirrors the way mails are formatted as text special header lines in the mail' text give its type ( plain text or multipart)as well as the separator used between the content of nested parts since the underlying textual details are automated by the email package--both when parsing and when composing--we won' go into further formatting details here if you are interested in seeing how this translates to real emailsa great way to learn mail structure is by inspecting the full raw text of messages displayed by email clients you already useas we'll see with some we meet in this book in factwe've already seen few--see the raw text printed by our earlier pop email scripts for simple mail text examples for more on the message objectand email in generalconsult the email package' entry in python' library manual we're skipping details such as its available encoders and mime object classes here in the interest of space beyond the email packagethe python library includes other tools for mail-related processing for instancemimetypes maps filename to and from mime typemimetypes guess_type(filenamemaps filename to mime type name spam txt maps to text/plan mimetypes guess_extension(contypemaps mime type to filename extension type text/html maps to html we also used the mimetypes module earlier in this to guess ftp transfer modes from filenames (see example - )as well as in where we used it to guess media player for filename (see the examples thereincluding playfile pyexample - for emailthese can come in handy when attaching files to new message (guess_typeand saving parsed attachments that do not provide filename (guess_extensionin factthis module' source code is fairly complete reference to mime types see the library manual for more on these tools emailparsing and composing mail content
5,491
although we can' provide an exhaustive reference herelet' step through simple interactive session to illustrate the fundamentals of email processing to compose the full text of message--to be delivered with smtplibfor instance--make messageassign headers to its keysand set its payload to the message body converting to string yields the mail text this process is substantially simpler and less error-prone than the manual text operations we used earlier in example - to build mail as stringsfrom email message import message message( ['from''jane doe ['to''pp @learning-python comm set_payload('the owls are not what they seem ' str(mprint(sfromjane doe topp @learning-python com the owls are not what they seem parsing message' text--like the kind you obtain with poplib--is similarly simpleand essentially the inversewe get back message object from the textwith keys for headers and payload for the bodys same as in prior interaction 'fromjane doe \ntopp @learning-python com\ \nthe owls are not from email parser import parser parser(parsestr(sx ['from''jane doe get_payload('the owls are not what they seem items([('from''jane doe ')('to''pp @learning-python com')so far this isn' much different from the older and now-defunct rfc modulebut as we'll see in momentthings get more interesting when there is more than one part for simple messages like this onethe message walk generator treats it as single-part mailof type plain textfor part in walk()print( get_content_type()print( get_payload()text/plain the owls are not what they seem client-side scripting
5,492
making mail with attachments is little more workbut not muchwe just make root message and attach nested message objects created from the mime type object that corresponds to the type of data we're attaching the mimetext classfor instanceis subclass of messagewhich is tailored for text partsand knows how to generate the right types of header information when printed mimeimage and mimeaudio similarly customize message for images and audioand also know how to apply base and other mime encodings to binary data the root message is where we store the main headers of the mailand we attach parts hereinstead of setting the entire payload--the payload is list nownot string mimemultipart is message that provides the extra header protocol we need for the rootfrom email mime multipart import mimemultipart message subclasses from email mime text import mimetext with extra headers+logic top mimemultipart(root message object top['from''art subtype default=mixed top['to''pp @learning-python comsub mimetext('nice red uniforms \ 'part message attachments sub mimetext(open('data txt'read()sub add_header('content-disposition''attachment'filename='data txt'top attach(sub top attach(sub when we ask for the texta correctly formatted full mail text is returnedseparators and allready to be sent with smtplib--quite trickif you've ever tried this by handtext top as_string(or dostr(topor print(topprint(textcontent-typemultipart/mixedboundary="=============== ==mime-version fromart topp @learning-python com --=============== =content-typetext/plaincharset="us-asciimime-version content-transfer-encoding bit nice red uniforms --=============== =content-typetext/plaincharset="us-asciimime-version content-transfer-encoding bit content-dispositionattachmentfilename="data txtline line line --=============== ==-emailparsing and composing mail content
5,493
message object just like the one we built to send the message walk generator allows us to step through each partfetching their types and payloadstext same as in prior interaction 'content-typemultipart/mixedboundary="=============== =="\nmime-ver from email parser import parser msg parser(parsestr(textmsg['from''art for part in msg walk()print(part get_content_type()print(part get_payload()print(multipart/mixed [text/plain nice red uniforms text/plain line line line multipart alternative messages (with text and html renditions of the same messagecan be composed and parsed in similar fashion because email clients are able to parse and compose messages with simple object-based apithey are freed to focus on userinterface instead of text processing unicodeinternationalizationand the python email package now that 've shown you how "coolthe email package isi unfortunately need to let you know that it' not completely operational in python the email package works as shown for simple messagesbut is severely impacted by python ' unicode/bytes string dichotomy in number of ways in shortthe email package in python is still somewhat coded to operate in the realm of str text strings because these have become unicode in xand because some tools that email uses are now oriented toward bytes stringswhich do not mix freely with stra variety of conflicts crop up and cause issues for programs that depend upon this module at this writinga new version of email is being developed which will handle bytes and unicode encodings betterbut the going consensus is that it won' be folded back into python until release or laterlong after this book' release although few patches client-side scripting
5,494
problems appears to require full redesign to be fairit' substantial problem email has historically been oriented toward singlebyte ascii textand generalizing it for unicode is difficult to do well in factthe same holds true for most of the internet today--as discussed elsewhere in this ftppopsmtpand even webpage bytes fetched over http pose the same sorts of issues interpreting the bytes shipped over networks as text is easy if the mapping is one-toonebut allowing for arbitrary unicode encoding in that text opens pandora' box of dilemmas the extra complexity is necessary todaybutas email attestscan be daunting task franklyi considered not releasing this edition of this book until this package' issues could be resolvedbut decided to go forward because new email package may be years away (two python releasesby all accountsmoreoverthe issues serve as case study of the types of problems you'll run into in the real world of large-scale software development things change over timeand program code is no exception insteadthis book' examples provide new unicode and internationalization support but adopt policies to work around issues where possible programs in books are meant to be educationalafter allnot commercially viable given the state of the email package that the examples depend onthoughthe solutions used here might not be completely universaland there may be additional unicode issues lurking to address the futurewatch this book' website (described in the prefacefor updated notes and code examples if/when the anticipated new email package appears herewe'll work with what we have the good news is that we'll be able to make use of email in its current form to build fairly sophisticated and full-featured email clients in this book anyhow it still offers an amazing number of toolsincluding mime encoding and decodingmessage formatting and parsinginternationalized headers extraction and constructionand more the bad news is that this will require handful of obscure workarounds and may need to be changed in the futurethough few software projects are exempt from such realities because email' limitations have implications for later email code in this booki' going to quickly run through them in this section some of this can be safely saved for later referencebut parts of later examples may be difficult to understand if you don' have this background the upside is that exploring the package' limitations here also serves as vehicle for digging bit deeper into the email package' interfaces in general parser decoding requirement the first unicode issue in python ' email package is nearly showstopper in some contextsthe bytes strings of the sort produced by poplib for mail fetches must be decoded to str prior to parsing with email unfortunatelybecause there may not be enough information to know how to decode the message bytes per unicodesome clients of this package may need to be generalized to detect whole-message encodings emailparsing and composing mail content
5,495
the current package cannot be used at all here' the issue livetext from prior example in his section 'content-typemultipart/mixedboundary="=============== =="\nmime-ver btext text encode(btext 'content-typemultipart/mixedboundary="=============== =="\nmime-ve msg parser(parsestr(textemail parser expects unicode str msg parser(parsestr(btextbut poplib fetches email as bytestraceback (most recent call last)file ""line in file " :\python \lib\email\parser py"line in parsestr return self parse(stringio(text)headersonly=headersonlytypeerrorinitial_value must be str or nonenot bytes msg parser(parsestr(btext decode()msg parser(parsestr(btext decode('utf ')msg parser(parsestr(btext decode('latin ')msg parser(parsestr(btext decode('ascii')okay per default ascii encoded (defaultascii is same in all this is less than idealas bytes-based email would be able to handle message encodings more directly as mentionedthoughthe email package is not really fully functional in python because of its legacy str focusand the sharp distinction that python makes between unicode text and byte strings in this caseits parser should accept bytes and not expect clients to know how to decode because of thatthis book' email clients take simplistic approaches to decoding fetched message bytes to be parsed by email specificallyfull-text decoding will try userconfigurable encoding namethen fall back on trying common types as heuristicand finally attempt to decode just message headers this will suffice for the examples shown but may need to be enhanced for broader applicability in some casesencoding may have to be determined by other schemes such as inspecting email headers (if present at all)guessing from bytes structure analysisor dynamic user feedback adding such enhancements in robust fashion is likely too complex to attempt in book' example codeand it is better performed in common standard library tools in any event reallyrobust decoding of mail text may not be possible today at allif it requires headers inspections--we can' inspect message' encoding information headers unless we parse the messagebut we can' parse message with ' email package unless we already know the encoding that isscripts may need to parse in order to decodebut they need to decode in order to parsethe byte strings of poplib and unicode strings of email in are fundamentally at odds even within its own librariespython ' changes have created chicken-and-egg dependency problem that still exists nearly two years after ' release client-side scripting
5,496
the best bet today for fetched messages seems to be decoding per user preferences and defaultsand that' how we'll proceed in this edition the pymailgui client of for instancewill allow unicode encodings for full mail text to be set on persession basis the real issueof courseis that email in general is inherently complicated by the presence of arbitrary text encodings besides full mail textwe also must consider unicode encoding issues for the text components of message once it' parsed--both its text parts and its message headers to see whylet' move on related issue for cgi scriptsi should also note that the full text decoding issue may not be as large factor for email as it is for some other email package clients because the original email standards call for ascii text and require binary data to be mime encodedmost emails are likely to decode properly according to or -bit encoding such as latin- as we'll see in thougha more insurmountable and related issue looms for server-side scripts that support cgi file uploads on the web--because python' cgi module also uses the email package to parse multipart form databecause this package requires data to be decoded to str for parsingand because such data might have mixed text and binary data (included raw binary data that is not mime-encodedtext of any encodingand even arbitrary combinations of these)these uploads fail in python if any binary or incompatible text files are included the cgi module triggers unicode decoding or type errors internallybefore the python script has chance to intervene cgi uploads worked in python xbecause the str type represented both possibly encoded text and binary data saving this type' content to binary mode file as string of bytes in sufficed for both arbitrary text and binary data such as images email parsing worked in for the same reason for better or worsethe str/bytes dichotomy makes this generality impossible in other wordsalthough we can generally work around the email parser' str requirement for fetched emails by decoding per an -bit encodingit' much more malignant for web scripting today watch for more details on this in and stay tuned for future fixwhich may have materialized by the time you read these words text payload encodingshandling mixed type results our next email unicode issue seems to fly in the face of python' generic programming modelthe data types of message payload objects may differdepending on how they are fetched especially for programs that walk and process payloads of mail parts genericallythis complicates code emailparsing and composing mail content
5,497
uuencodequoted-printableif this argument is passed in as (or equivalentlytrue)the payload' data is mime-decoded when fetchedif required because this argument is so useful for complex messages with arbitrary partsit will normally be passed as true in all cases binary parts are normally mime-encodedbut even text parts might also be present in base or another mime form if their bytes fall outside email standards some types of unicode textfor examplerequire mime encoding the upshot is that get_payload normally returns str strings for str text partsbut returns bytes strings if its decode argument is true--even if the message part is known to be text by nature if this argument is not usedthe payload' type depends upon how it was setstr or bytes because python does not allow str and bytes to be mixed freelyclients that need to use the result in text processing or store it in files need to accommodate the difference let' run some code to illustratefrom email message import message message( ['from''lancelotm set_payload('line' ['from''lancelotm get_payload('linem get_payload(decode= 'linestrif payload is str bytesif mime decode (same as decode=truethe combination of these different return types and python ' strict str/bytes dichotomy can cause problems in code that processes the result unless they decode carefullym get_payload(decode=true'spamtypeerrorcan' concat bytes to str get_payload(decode=truedecode('spam'linespamcan' mix in xconvert if required to make sense of these examplesit may help to remember that there are two different concepts of "encodingfor email textemail-style mime encodings such as base uuencodeand quoted-printablewhich are applied to binary and otherwise unusual content to make them acceptable for transmission in email text unicode text encodings for strings in generalwhich apply to message text as well as its partsand may be required after mime encoding for text message parts the email package handles email-style mime encodings automatically when we pass decode= to fetch parsed payloadsor generate text for messages that have nonprintable partsbut scripts still need to take unicode encodings into consideration because of client-side scripting
5,498
following refers to mimeand the second to unicodem get_payload(decode=truedecode(to bytes via mimethen to str via unicode even without the mime decode argumentthe payload type may also differ if it is stored in different formsm message() set_payload('spam') get_payload('spamm message() set_payload( 'spam') get_payload( 'spamfetched as stored moreoverthe same hold true for the text-specific mime subclass (though as we'll see later in this sectionwe cannot pass bytes to its constructor to force binary payload)from email mime text import mimetext mimetext('line ?' ['from''lancelotm['from''lancelotm get_payload('line ? get_payload(decode= 'line ?unfortunatelythe fact that payloads might be either str or bytes today not only flies in the face of python' type-neutral mindsetit can complicate your code--scripts may need to convert in contexts that require one or the other type for instancegui libraries might allow bothbut file saves and web page content generation may be less flexible in our example programswe'll process payloads as bytes whenever possiblebut decode to str text in cases where required using the encoding information available in the header api described in the next section text payload encodingsusing header information to decode more profoundlytext in email can be even richer than implied so far--in principletext payloads of single message may be encoded in variety of different unicode schemes ( three html webpage file attachmentsall in different unicode encodingsand possibly different than the full message text' encodingalthough treating such text as binary byte strings can sometimes finesse encoding issuessaving such parts in text-mode files for opening must respect the original encoding types furtherany text processing performed on such parts will be similarly type-specific luckilythe email package both adds character-set headers when generating message text and retains character-set information for parts if it is present when parsing message text for instanceadding non-ascii text attachments simply requires passing in an encoding name--the appropriate message headers are added automatically on text generationand the character set is available directly via the get_content_charset methodemailparsing and composing mail content
5,499
decode('latin ''aabfrom email message import message message( set_payload( ' \xe 'charset='latin ' as_string(print(tmime-version content-typetext/plaincharset="latin content-transfer-encodingbase or 'latin- 'see ahead qerc get_content_charset('latin notice how email automatically applies base mime encoding to non-ascii text parts on generationto conform to email standards the same is true for the more specific mime text subclass of messagefrom email mime text import mimetext mimetext( ' \xe '_charset='latin ' as_string(print(tcontent-typetext/plaincharset="latin mime-version content-transfer-encodingbase qerc get_content_charset('latin nowif we parse this message' text string with emailwe get back new message whose text payload is the base mime-encoded text used to represent the non-ascii unicode string requesting mime decoding for the payload with decode= returns the byte string we originally attachedfrom email parser import parser parser(parsestr(tq get_content_type('text/plainq _payload 'qerc\nq get_payload('qerc\nq get_payload(decode= ' \xe bhoweverrunning unicode decoding on this byte string to convert to text fails if we attempt to use the platform default on windows (utf to be more accurateand client-side scripting