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

(yzsuai) #1
.txt ('text/plain', None)
.py ('text/x-python', None)
.pyw (None, None)
.html ('text/html', None)
.c ('text/plain', None)
.h ('text/plain', None)
.xml ('text/xml', None)

We can add this technique to our earlier SearchVisitor class by redefining its candidate
selection method, in order to replace its default extension lists with mimetypes guesses—
yet more evidence of the power of OOP customization at work:


C:\...\PP4E\Tools> python
>>> import mimetypes
>>> from visitor import SearchVisitor # or PP4E.Tools.visitor if not.
>>>
>>> class SearchMimeVisitor(SearchVisitor):
... def candidate(self, fname):
... contype, encoding = mimetypes.guess_type(fname)
... return (contype and
... contype.split('/')[0] == 'text' and
... encoding == None)

>>> V = SearchMimeVisitor('mimetypes', trace=0) # search key
>>> V.run(r'C:\temp\PP3E\Examples') # root dir
C:\temp\PP3E\Examples\PP3E\extras\LosAlamosAdvancedClass\day1-system\data.txt ha
s mimetypes
C:\temp\PP3E\Examples\PP3E\Internet\Email\mailtools\mailParser.py has mimetypes
C:\temp\PP3E\Examples\PP3E\Internet\Email\mailtools\mailSender.py has mimetypes
C:\temp\PP3E\Examples\PP3E\Internet\Ftp\mirror\downloadflat.py has mimetypes
C:\temp\PP3E\Examples\PP3E\Internet\Ftp\mirror\downloadflat_modular.py has mimet
ypes
C:\temp\PP3E\Examples\PP3E\Internet\Ftp\mirror\ftptools.py has mimetypes
C:\temp\PP3E\Examples\PP3E\Internet\Ftp\mirror\uploadflat.py has mimetypes
C:\temp\PP3E\Examples\PP3E\System\Media\playfile.py has mimetypes
>>> V.scount, V.fcount, V.dcount
(8, 1429, 186)

Because this is not completely accurate, though (you may need to add logic to include
extensions like “.pyw” missed by the guess), and because it’s not even appropriate for
all search clients (some may want to search specific kinds of text only), this scheme was
not used for the original class. Using and tailoring it for your own searches is left as
optional exercise.


Running the Script


Now, when Example 6-23 is run from the command line, if all goes well its canned self-
test code at the end opens a number of audio, image, text, and other file types located
in the script’s directory, using either platform-specific players or a general web browser.
On my Windows 7 laptop, GIF and HTML files open in new IE browser tabs; JPEG
files in Windows Photo Viewer; plain text files in Notepad; DOC and XLS files in
Microsoft Word and Excel; and audio files in Windows Media Player.


350 | Chapter 6: Complete System Programs

Free download pdf