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

(yzsuai) #1

On Windows, for example, all three simply run os.startfile by default and thus create
a new tab in an existing window under Internet Explorer 8. This is also why I didn’t
need the “file://” full URL prefix in the preceding listing. Technically, Internet Explorer
is only run if this is what is registered on your computer for the file type being opened;
if not, that file type’s handler is opened instead. Some images, for example, may open
in a photo viewer instead. On other platforms, such as Unix and Mac OS X, browser
behavior differs, and non-URL file names might not be opened; use “file://” for
portability.


We’ll use this module again later in this book. For example, the PyMailGUI program
in Chapter 14 will employ it as a way to display HTML-formatted email messages and
attachments, as well as program help. See the Python library manual for more details.
In Chapters 13 and 15, we’ll also meet a related call, urllib.request.urlopen, which
fetches a web page’s text given a URL, but does not open it in a browser; it may be
parsed, saved, or otherwise used.


The Python mimetypes Module


To make this media player module even more useful, we also use the Python
mimetypes standard library module to automatically determine the media type from the
filename. We get back a type/subtype MIME content-type string if the type can be
determined or None if the guess failed:


>>> import mimetypes
>>> mimetypes.guess_type('spam.jpg')
('image/jpeg', None)

>>> mimetypes.guess_type('TheBrightSideOfLife.mp3')
('audio/mpeg', None)

>>> mimetypes.guess_type('lifeofbrian.mpg')
('video/mpeg', None)

>>> mimetypes.guess_type('lifeofbrian.xyz') # unknown type
(None, None)

Stripping off the first part of the content-type string gives the file’s general media type,
which we can use to select a generic player; the second part (subtype) can tell us if text
is plain or HTML:


>>> contype, encoding = mimetypes.guess_type('spam.jpg')
>>> contype.split('/')[0]
'image'

>>> mimetypes.guess_type('spam.txt') # subtype is 'plain'
('text/plain', None)

>>> mimetypes.guess_type('spam.html')
('text/html', None)

348 | Chapter 6: Complete System Programs

Free download pdf