12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

import oopssafe(oops.oops)% python safe2.pyTraceback (innermost last):File "safe2.py", line 5, in safeapply(entry, args)File "oops.py", line 4, in oopsraise MyError, 'world'hello: worldGot hello world# Catch everything elseToday, I would probably code this as follows, using the newer *args call syntaxand exc_info:def safe(entry, *args):try:entry(*args)# Catch everything elseexcept:traceback.print_exc( )print 'Got', sys.exc_info( ){0], sys.exc_info( )[1]4. Here are a few examples for you to study as time allows; for more, see follow-upbooks and the Web:# Find the largest file in a single directorydirname = r'C:\<strong>Python</strong>25\Lib'import os, globallsizes = []allpy = glob.glob(os.path.join(dirname, '*.py'))for filename in allpy:filesize = os.path.getsize(filename)allsizes.append((filesize, filename))allsizes.sort( )print allsizes[:2]print allsizes[-2:]# Find the largest file in an entire directory treeimport sysif sys.platform[:3] == 'win':dirname = r'C:\<strong>Python</strong>25\Lib'else:dirname = '/usr/lib/python'import os, globallsizes = []for (thisDir, subsHere, filesHere) in os.walk(dirname):for filename in filesHere:if filename.endswith('.py'):fullname = os.path.join(thisDir, filename)fullsize = os.path.getsize(fullname)allsizes.append((fullsize, fullname))674 | Appendix B: Solutions to End-of-Part Exercises

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

Saved successfully!

Ooh no, something went wrong!