12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

140 Chapter 14. FilesThepicklemodulecanhelp. Ittranslatesalmostanytypeofobjectintoastringsuitableforstorageinadatabase, and then translates stringsback intoobjects.pickle.dumpstakesanobjectasaparameterandreturnsastringrepresentation(dumpsisshortfor“dump string”):>>> import pickle>>> t = [1, 2, 3]>>> pickle.dumps(t)'(lp0\nI1\naI2\naI3\na.'The format isn’t obvious to human readers; it is meant to be easy for pickle to interpret.pickle.loads(“load string”) reconstitutes the object:>>> t1 = [1, 2, 3]>>> s = pickle.dumps(t1)>>> t2 = pickle.loads(s)>>> print t2[1, 2, 3]Although thenew object has thesame value asthe old, itisnot (ingeneral) the sameobject:>>> t1 == t2True>>> t1 is t2FalseInother words, pickling and then unpickling has the sameeffect ascopying theobject.You can use pickle to store non-strings in a database. In fact, this combination is so common thatithas been encapsulated inamodule calledshelve.Exercise14.3 IfyoudidExercise12.4,modifyyoursolutionsothatitcreatesadatabasethatmapsfrom each word inthelisttoalistof words that use thesame setof letters.Writeadifferentprogramthatopensthedatabaseandprintsthecontentsinahuman-readableformat.14.8 PipesMost operating systems provide a command-line interface, also known as a shell. Shells usuallyprovide commands to navigate the file system and launch applications. For example, in Unix, youcanchangedirectorieswithcd,displaythecontentsofadirectorywithls,andlaunchawebbrowserby typing (forexample)firefox.Any program that you can launch from the shell can also be launched from <strong>Python</strong> using a pipe. Apipe isan object that represents arunning process.For example, the Unix command ls -l normally displays the contents of the current directory (inlong format). You can launchlswithos.popen:>>> cmd = 'ls -l'>>> fp = os.popen(cmd)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!