12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

14.9. Writingmodules 141The argument is a string that contains a shell command. The return value is an object that behavesjustlikeanopenfile. Youcanreadtheoutputfromthelsprocessonelineatatimewithreadlineor get the whole thingat once withread:>>> res = fp.read()When you are done, you close thepipe likeafile:>>> stat = fp.close()>>> print statNoneThe return value is the final status of the ls process; None means that it ended normally (with noerrors).A common use of pipes is to read a compressed file incrementally; that is, without uncompressingthe whole thing at once. The following function takes the name of a compressed file as a parameterand returns apipe that usesgunziptodecompress thecontents:def open_gunzip(filename):cmd = 'gunzip -c ' + filenamefp = os.popen(cmd)return fpIfyoureadlinesfromfponeatatime,youneverhavetostoretheuncompressedfileinmemoryoron disk.14.9 WritingmodulesAny file that contains <strong>Python</strong> code can be imported as a module. For example, suppose you have afilenamedwc.pywiththefollowing code:def linecount(filename):count = 0for line in open(filename):count += 1return countprint linecount('wc.py')If you run this program, it reads itself and prints the number of lines in the file, which is 7. You canalsoimport itlikethis:>>> import wc7Now you have amodule objectwc:>>> print wcThat provides afunction calledlinecount:

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

Saved successfully!

Ooh no, something went wrong!