[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

else:
trywebbrowser(filename, **options) # general scheme


def playfile(filename, mimetable=mimetable, options):
"""
play media file of any type: uses mimetypes to guess media
type and map to platform-specific player tables; spawn web
browser if text/html, media type unknown, or has no table
"""
contenttype, encoding = mimetypes.guess_type(filename) # check name
if contenttype == None or encoding is not None: # can't guess
contenttype = '?/?' # poss .txt.gz
maintype, subtype = contenttype.split('/', 1) # 'image/jpeg'
if maintype == 'text' and subtype == 'html':
trywebbrowser(filename,
options) # special case
elif maintype in mimetable:
playknownfile(filename, mimetable[maintype], options) # try table
else:
trywebbrowser(filename,
options) # other types


###############################################################################


self-test code


###############################################################################


if name == 'main':


media type known


playknownfile('sousa.au', audiotools, wait=True)
playknownfile('ora-pp3e.gif', imagetools, wait=True)
playknownfile('ora-lp4e.jpg', imagetools)


media type guessed


input('Stop players and press Enter')
playfile('ora-lp4e.jpg') # image/jpeg
playfile('ora-pp3e.gif') # image/gif
playfile('priorcalendar.html') # text/html
playfile('lp4e-preface-preview.html') # text/html
playfile('lp-code-readme.txt') # text/plain
playfile('spam.doc') # app
playfile('spreadsheet.xls') # app
playfile('sousa.au', wait=True) # audio/basic
input('Done') # stay open if clicked


Although it’s generally possible to open most media files by passing their names to a
web browser these days, this module provides a simple framework for launching media
files with more specific tools, tailored by both media type and platform. A web browser
is used only as a fallback option, if more specific tools are not available. The net result
is an extendable media file player, which is as specific and portable as the customiza-
tions you provide for its tables.


We’ve seen the program launch tools employed by this script in prior chapters. The
script’s main new concepts have to do with the modules it uses: the webbrowser module
to open some files in a local web browser, as well as the Python mimetypes module to


346 | Chapter 6: Complete System Programs

Free download pdf