faqts : Computers : Programming : Languages : Python : Platforms : Windows

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

59 of 69 people (86%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How can I use Python to start the default web browser on Win32?
How can I start other Windows programs from Python?

May 31st, 2001 21:07
Fred Drake, Nathan Wallace, Sean Blakey, Mark Hammond, Oliver Schaefer


Starting with Python 2.0, the easiest way to start the default Web
browser, but not other applications, is to use Python's webbrowser module:
  >>> import webbrowser
  >>> webbrowser.open("http://www.python.org/doc/")
Documentation for this module can be found at:
  http://www.python.org/doc/current/lib/module-webbrowser.html
This module cannot be used to start applications other than the Web browser.
  -Fred
---------------
The easiest way I know of is to use the windows "start" command (which
launches a program or opens a document in the associated program) to
open a url.  For example:
  >>import os
  >>my_url = 'http://www.python.org/'
  >>os.system('start %s' % my_url)
Alternatively you can use win32api.ShellExecute() if you have the
win32all extensions installed...
Here is some code using DDE that might help:
[code]------------------------------------------------------------------
#! python
# dde_op.py
"""\
preview support with dde and WinExec.
Usage:
(assuming the builtin __debug__ is set to 1)
>>> import dde_op
>>> dde_op.preview(r'file:///D:/Programme/Python/Doc/index.html')
hkey: -1070463376
value of key ".html": htmlfile
hkey: -1055374168
value of key "command": "D:\PROGRA~1\INTERN~1\iexplore.exe" -nohome
execute('"D:\PROGRA~1\INTERN~1\iexplore.exe" -nohome',
        '"file:///D:/Programme/Python/Doc/index.html"',
        '"file:///D:/Programme/Python/Doc/index.html"',
        'WWW_OpenURL', 'IExplore')
dde_exec('"D:\PROGRA~1\INTERN~1\iexplore.exe" -nohome',
         '"file:///D:/Programme/Python/Doc/index.html"',
         'WWW_OpenURL', 'IExplore')
connected
error: Exec failed  ### this happens every time with Internet Explorer
                    ### but works anyway!
>>>
Hint: if you don't want debugging support, remove debug() calls...
"""
import sys
from cStringIO import StringIO
from string import lower, rfind
# import some of Mark Hammond's Windows extensions...
from win32api import RegOpenKey, RegQueryValue, RegCloseKey, WinExec
from win32con import HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, \
     HKEY_CLASSES_ROOT
from dde import CreateServer, CreateTopic, CreateConversation
### debugging support ###
class Debug:
    def __init__(self, state):
        self.state = state
        self.write = sys.stderr.write
    def on(self):
        self.state = 1
    def off(self):
        self.state = 0
    def __nonzero__(self):
        return self.state
    def __call__(self, arg):
        self.state and self.write('%s\n' % arg)
# class Debug
import __builtin__
__builtin__.debug = Debug(__debug__)
del __builtin__, Debug
### dde support ###
def dde_exec(app, cmd, topic=None, service=None):
    if topic is None:
        topic = "WWW_OpenURL"
    if service is None:
        service = "NSShell"
    server = CreateServer()
    server.Create(app)
    Topic = CreateTopic(topic)
    server.AddTopic(Topic)
    conv = CreateConversation(server)
    ret = None
    try:
        conv.ConnectTo(service, topic)
        if conv.Connected():
            debug('connected')
            # conv.Exec sometimes complained, but every time
            # conv.Connected() was true, conv.Exec did the
            # job anyway...
            ret = 'success'
            conv.Exec(cmd)
            debug('success')
    except:
        etype, evalue = sys.exc_info()[:2]
        debug("%s: %s" % (etype, evalue))
    server.Destroy()
    return ret
# def dde_exec(app, cmd, topic=None, service=None)
def execute(app, cmd, dde_cmd=None, topic=None, service=None):
    """\
    Execute an app; if possible with dde, otherwise with WinExec.
    """
    if topic is None:
        topic = "WWW_OpenURL"
    if service is None:
        service = "NSShell"
    if dde_cmd is None:
        dde_cmd = cmd
    try:
        debug("dde_exec('%s', '%s', '%s', '%s')" % (app, dde_cmd,
                                                    topic, service))
        if not dde_exec(app, dde_cmd, topic, service):
            debug("WinExec('%s' '%s')" % (app, cmd))
            WinExec("%s %s" % (app, cmd))
    except:
        etype, evalue = sys.exc_info()[:2]
        debug("%s: %s" % (etype, evalue))
# def execute(app, cmd, dde_cmd=None, topic=None, service=None)
### registry support ###
def RegDefaultValue(name, hkey=None, subkey=None):
    if hkey is None:
        hkey = HKEY_LOCAL_MACHINE
    if subkey is None:
        subkey = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths'
    try:
        hkey = RegOpenKey(hkey, subkey)
        debug('hkey: %d' % hkey.handle)
        value = RegQueryValue(hkey, name)
        debug('value of key "%s": %s' % (name, value))
    except:
        etype, evalue = sys.exc_info()[:2]
        debug("%s: %s" % (etype, evalue))
        value = None
    RegCloseKey(hkey)
    return value
# def RegDefaultValue(name, hkey=None, subkey=None)
def RegGetValue(name, hkey=None, subkey=None):
    if hkey is None:
        hkey = HKEY_LOCAL_MACHINE
    if subkey is None:
        subkey = ''
    try:
        hkey = RegOpenKey(hkey, subkey)
        debug('hkey: %d' % hkey.handle)
        value, type = RegQueryValueEx(hkey, name)
        debug('value of "%s": %s (type = %s)' % (name, value, type))
    except:
        etype, evalue = sys.exc_info()[:2]
        debug("%s: %s" % (etype, evalue))
        value = None
    RegCloseKey(hkey)
    return value
# def RegGetValue(name, hkey=None, subkey=None)
### main part of the preview method for Template/HTML objects ###
def preview(src, browser='default'):
    if not src:
        raise ValueError, 'object is not associated with a source file'
    cmd = '"%s"' % src # src can be an instance with __str__ method
    app = lower(browser)
    topic = "WWW_OpenURL"
    dde_cmd = cmd
    stderr, sys.stderr = sys.stderr, StringIO()
    try:
        if app == 'default':
            key = RegDefaultValue('.html', HKEY_CLASSES_ROOT, '')
            if not key:
                raise ValueError, 'no default web browser registered'
            key = r'%s\shell\open' % key
            app = RegDefaultValue('command', HKEY_CLASSES_ROOT, key)
            if rfind(lower(app), 'iexplore.exe') != -1:
                service = "IExplore"
            else:
                service = "NSShell"
        elif app in ('netscape', 'navigator', 'communicator'):
            app = RegDefaultValue('NETSCAPE.EXE')
            service = "NSShell"
        elif app in ('ie', 'iexplore', 'internet explorer', 'explorer'):
            app = RegDefaultValue('IEXPLORE.EXE')
            service = "IExplore"
        else:
            app = RegDefaultValue(browser) or browser
            topic = "System"
            pos1 = rfind(browser, '\\') + 1
            pos2 = rfind(browser, '.')
            if pos2 == -1: pos2 = len(browser)
            service = browser[pos1:pos2]
        debug("execute('%s', '%s', '%s', '%s', '%s')" % \
              (app, cmd, dde_cmd, topic, service))
        execute(app, cmd, dde_cmd, topic, service)
    finally:
        sys.stderr, stderr = stderr, sys.stderr
        debug(stderr.getvalue())
# def preview(src, browser='default')
def test(arg=None):
    if arg:
        preview(arg[1])
    else:
        try:
            src = raw_input('file to previw: ')
        except KeyboardInterrupt:
            src = None
        if src:
            preview(src)
        else:
            print 'filename not valid.'
# def test(arg=None)
if __name__ == '__main__':
    test(sys.argv[1:])
[/code]----------------------------------------------------------------