determine media type from file name. Since these are the heart of this code’s matter,
let’s explore these briefly before we run the script.
The Python webbrowser Module
The standard library webbrowser module used by this example provides a portable in-
terface for launching web browsers from Python scripts. It attempts to locate a suitable
web browser on your local machine to open a given URL (file or web address) for
display. Its interface is straightforward:
>>> import webbrowser
>>> webbrowser.open_new('file://' + fullfilename) # use os.path.abspath()
This code will open the named file in a new web browser window using whatever
browser is found on the underlying computer, or raise an exception if it cannot. You
can tailor the browsers used on your platform, and the order in which they are attemp-
ted, by using the BROWSER environment variable and register function. By default,
webbrowser attempts to be automatically portable across platforms.
Use an argument string of the form “file://...” or “http://...” to open a file on the local
computer or web server, respectively. In fact, you can pass in any URL that the browser
understands. The following pops up Python’s home page in a new locally-running
browser window, for example:
>>> webbrowser.open_new('http://www.python.org')
Among other things, this is an easy way to display HTML documents as well as media
files, as demonstrated by this section’s example. For broader applicability, this module
can be used as both command-line script (Python’s -m module search path flag helps
here) and as importable tool:
C:\Users\mark\Stuff\Websites\public_html> python -m webbrowser about-pp.html
C:\Users\mark\Stuff\Websites\public_html> python -m webbrowser -n about-pp.html
C:\Users\mark\Stuff\Websites\public_html> python -m webbrowser -t about-pp.html
C:\Users\mark\Stuff\Websites\public_html> python
>>> import webbrowser
>>> webbrowser.open('about-pp.html') # reuse, new window, new tab
True
>>> webbrowser.open_new('about-pp.html') # file:// optional on Windows
True
>>> webbrowser.open_new_tab('about-pp.html')
True
In both modes, the difference between the three usage forms is that the first tries to
reuse an already-open browser window if possible, the second tries to open a new
window, and the third tries to open a new tab. In practice, though, their behavior is
totally dependent on what the browser selected on your platform supports, and even
on the platform in general. All three forms may behave the same.
Playing Media Files | 347