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

(yzsuai) #1

import os, sys, mimetypes, webbrowser


helpmsg = """
Sorry: can't find a media player for '%s' on your system!
Add an entry for your system to the media player dictionary
for this type of file in playfile.py, or play the file manually.
"""


def trace(args): print(args) # with spaces between


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


player techniques: generic and otherwise: extend me


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


class MediaTool:
def init(self, runtext=''):
self.runtext = runtext
def run(self, mediafile, options): # most ignore options
fullpath = os.path.abspath(mediafile) # cwd may be anything
self.open(fullpath,
options)


class Filter(MediaTool):
def open(self, mediafile, **ignored):
media = open(mediafile, 'rb')
player = os.popen(self.runtext, 'w') # spawn shell tool
player.write(media.read()) # send to its stdin


class Cmdline(MediaTool):
def open(self, mediafile, **ignored):
cmdline = self.runtext % mediafile # run any cmd line
os.system(cmdline) # use %s for filename


class Winstart(MediaTool): # use Windows registry
def open(self, mediafile, wait=False, **other): # or os.system('start file')
if not wait: # allow wait for curr media
os.startfile(mediafile)
else:
os.system('start /WAIT ' + mediafile)


class Webbrowser(MediaTool):


file:// requires abs path


def open(self, mediafile, options):
webbrowser.open_new('file://%s' % mediafile,
options)


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


media- and platform-specific policies: change me, or pass one in


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


map platform to player: change me!


audiotools = {
'sunos5': Filter('/usr/bin/audioplay'), # os.popen().write()
'linux2': Cmdline('cat %s > /dev/audio'), # on zaurus, at least
'sunos4': Filter('/usr/demo/SOUND/play'), # yes, this is that old!


344 | Chapter 6: Complete System Programs

Free download pdf