Skip to content

Instantly share code, notes, and snippets.

@endolith
Created June 13, 2009 21:33
Show Gist options
  • Save endolith/129441 to your computer and use it in GitHub Desktop.
Save endolith/129441 to your computer and use it in GitHub Desktop.
Python browser shortcuts
#!/usr/bin/env python
"""Some utilities for working with the web browser
function call_browser(url) opens url in the user's default browser
function browser_render(html) sends HTML to the user's default browser for display
"""
import tempfile
import time
import commands
import thread
# Jython doesn't have this
if 'java' not in os.name:
import webbrowser
def call_browser(url="http://www.example.com"):
'''Calls the user's default web browser to upen the URL.
Tries to use cross-platform xdg-open tool first. If that fails
(xdg-utils not installed or some other error), falls back to Python's
built-in, but less-than-optimal solution.
(From rnghelpers.py in Reportbug-NG (GPL) by Bastian Venthur)
http://blog.venthur.de/2007/07/01/python-osfork-webbrowser-and-debbugs/
'''
status, output = commands.getstatusoutput('xdg-open "%s"' % url)
if status != 0 and 'java' not in os.name:
print("xdg-open %s returned (%i, %s), falling back to python's "
"webbrowser.open" % (url, status, output))
thread.start_new_thread(webbrowser.open, (url,))
def browser_render(html="<h1>nothing supplied to function</h1>"):
'''Displays a string of HTML in the user's default browser
The HTML is stored in a temporary file and opened with call_browser()
(If the browser doesn't open within 5 seconds, the temporary file will be
deleted before it can be opened)
'''
f = tempfile.NamedTemporaryFile(suffix=".html")
f.write(str(html))
f.flush()
call_browser(f.name)
# Since the tempfile is erased IMMEDIATELY and the browser doesn't have time to open it.
time.sleep(5)
def main():
print "Sending test HTML to default browser..."
page = '''<h3>If you can see <u>this</u>,</h3> <code>browser_render()</code>
and <code>call_browser()</code> are <i>working</i>'''
browser_render(page)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment