webbrowser.py 20.5 KB
Newer Older
1
#! /usr/bin/env python
2
"""Interfaces for launching and remotely controlling Web browsers."""
3
# Maintained by Georg Brandl.
4 5

import os
6
import shlex
7
import sys
8
import stat
9 10
import subprocess
import time
11

12
__all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"]
13

14 15 16
class Error(Exception):
    pass

Tim Peters's avatar
Tim Peters committed
17 18
_browsers = {}          # Dictionary of available browser controllers
_tryorder = []          # Preference order of available browsers
19

20
def register(name, klass, instance=None, update_tryorder=1):
21 22
    """Register a browser connector and, optionally, connection."""
    _browsers[name.lower()] = [klass, instance]
23 24 25 26
    if update_tryorder > 0:
        _tryorder.append(name)
    elif update_tryorder < 0:
        _tryorder.insert(0, name)
27

28 29
def get(using=None):
    """Return a browser launcher instance appropriate for the environment."""
30
    if using is not None:
31 32 33 34
        alternatives = [using]
    else:
        alternatives = _tryorder
    for browser in alternatives:
35
        if '%s' in browser:
36
            # User gave us a command line, split it into name and args
37 38 39 40 41
            browser = shlex.split(browser)
            if browser[-1] == '&':
                return BackgroundBrowser(browser[:-1])
            else:
                return GenericBrowser(browser)
42
        else:
43
            # User gave us a browser name or path.
44 45 46 47
            try:
                command = _browsers[browser.lower()]
            except KeyError:
                command = _synthesize(browser)
48
            if command[1] is not None:
49
                return command[1]
50 51
            elif command[0] is not None:
                return command[0]()
52
    raise Error("could not locate runnable browser")
53 54

# Please note: the following definition hides a builtin function.
55 56
# It is recommended one does "import webbrowser" and uses webbrowser.open(url)
# instead of "from webbrowser import *".
57

58
def open(url, new=0, autoraise=1):
59 60 61 62 63
    for name in _tryorder:
        browser = get(name)
        if browser.open(url, new, autoraise):
            return True
    return False
64

Fred Drake's avatar
Fred Drake committed
65
def open_new(url):
66
    return open(url, 1)
67

68 69
def open_new_tab(url):
    return open(url, 2)
70

71 72

def _synthesize(browser, update_tryorder=1):
73 74 75 76 77 78 79 80 81 82 83
    """Attempt to synthesize a controller base on existing controllers.

    This is useful to create a controller when a user specifies a path to
    an entry in the BROWSER environment variable -- we can copy a general
    controller to operate using a specific installation of the desired
    browser in this way.

    If we can't create a controller in this way, or if there is no
    executable for the requested browser, return [None, None].

    """
84 85
    cmd = browser.split()[0]
    if not _iscommand(cmd):
86
        return [None, None]
87
    name = os.path.basename(cmd)
88 89 90 91 92 93 94 95 96 97 98
    try:
        command = _browsers[name.lower()]
    except KeyError:
        return [None, None]
    # now attempt to clone to fit the new name:
    controller = command[1]
    if controller and name.lower() == controller.basename:
        import copy
        controller = copy.copy(controller)
        controller.name = browser
        controller.basename = os.path.basename(browser)
99
        register(browser, None, controller, update_tryorder)
100
        return [None, controller]
101
    return [None, None]
102

Fred Drake's avatar
Fred Drake committed
103

104 105 106
if sys.platform[:3] == "win":
    def _isexecutable(cmd):
        cmd = cmd.lower()
107
        if os.path.isfile(cmd) and cmd.endswith((".exe", ".bat")):
108 109 110 111 112 113 114 115 116 117 118 119 120
            return True
        for ext in ".exe", ".bat":
            if os.path.isfile(cmd + ext):
                return True
        return False
else:
    def _isexecutable(cmd):
        if os.path.isfile(cmd):
            mode = os.stat(cmd)[stat.ST_MODE]
            if mode & stat.S_IXUSR or mode & stat.S_IXGRP or mode & stat.S_IXOTH:
                return True
        return False

Fred Drake's avatar
Fred Drake committed
121
def _iscommand(cmd):
122 123 124 125
    """Return True if cmd is executable or can be found on the executable
    search path."""
    if _isexecutable(cmd):
        return True
Fred Drake's avatar
Fred Drake committed
126 127
    path = os.environ.get("PATH")
    if not path:
128
        return False
Fred Drake's avatar
Fred Drake committed
129 130
    for d in path.split(os.pathsep):
        exe = os.path.join(d, cmd)
131
        if _isexecutable(exe):
132 133
            return True
    return False
Fred Drake's avatar
Fred Drake committed
134 135


136 137 138
# General parent classes

class BaseBrowser(object):
139
    """Parent class for all browsers. Do not use directly."""
Tim Peters's avatar
Tim Peters committed
140

141
    args = ['%s']
Tim Peters's avatar
Tim Peters committed
142

143 144
    def __init__(self, name=""):
        self.name = name
145
        self.basename = name
Tim Peters's avatar
Tim Peters committed
146

Neal Norwitz's avatar
Neal Norwitz committed
147 148 149
    def open(self, url, new=0, autoraise=1):
        raise NotImplementedError

150 151 152 153 154 155
    def open_new(self, url):
        return self.open(url, 1)

    def open_new_tab(self, url):
        return self.open(url, 2)

Fred Drake's avatar
Fred Drake committed
156

157 158 159
class GenericBrowser(BaseBrowser):
    """Class for all browsers started with a command
       and without remote functionality."""
Fred Drake's avatar
Fred Drake committed
160

161 162 163
    def __init__(self, name):
        if isinstance(name, basestring):
            self.name = name
164
            self.args = ["%s"]
165 166 167 168
        else:
            # name should be a list with arguments
            self.name = name[0]
            self.args = name[1:]
169
        self.basename = os.path.basename(self.name)
Fred Drake's avatar
Fred Drake committed
170 171

    def open(self, url, new=0, autoraise=1):
Tim Peters's avatar
Tim Peters committed
172
        cmdline = [self.name] + [arg.replace("%s", url)
173 174
                                 for arg in self.args]
        try:
175 176 177 178
            if sys.platform[:3] == 'win':
                p = subprocess.Popen(cmdline)
            else:
                p = subprocess.Popen(cmdline, close_fds=True)
179 180 181 182 183 184 185 186 187 188 189 190 191
            return not p.wait()
        except OSError:
            return False


class BackgroundBrowser(GenericBrowser):
    """Class for all browsers which are to be started in the
       background."""

    def open(self, url, new=0, autoraise=1):
        cmdline = [self.name] + [arg.replace("%s", url)
                                 for arg in self.args]
        try:
192 193 194 195 196 197 198
            if sys.platform[:3] == 'win':
                p = subprocess.Popen(cmdline)
            else:
                setsid = getattr(os, 'setsid', None)
                if not setsid:
                    setsid = getattr(os, 'setpgrp', None)
                p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid)
199 200 201
            return (p.poll() is None)
        except OSError:
            return False
Fred Drake's avatar
Fred Drake committed
202 203


204 205
class UnixBrowser(BaseBrowser):
    """Parent class for all Unix browsers with remote functionality."""
Fred Drake's avatar
Fred Drake committed
206

207
    raise_opts = None
208
    remote_args = ['%action', '%s']
209 210 211
    remote_action = None
    remote_action_newwin = None
    remote_action_newtab = None
212 213 214 215 216 217 218 219 220 221 222 223
    background = False
    redirect_stdout = True

    def _invoke(self, args, remote, autoraise):
        raise_opt = []
        if remote and self.raise_opts:
            # use autoraise argument only for remote invocation
            autoraise = int(bool(autoraise))
            opt = self.raise_opts[autoraise]
            if opt: raise_opt = [opt]

        cmdline = [self.name] + raise_opt + args
Tim Peters's avatar
Tim Peters committed
224

225 226 227 228 229 230 231 232 233 234
        if remote or self.background:
            inout = file(os.devnull, "r+")
        else:
            # for TTY browsers, we need stdin/out
            inout = None
        # if possible, put browser in separate process group, so
        # keyboard interrupts don't affect browser as well as Python
        setsid = getattr(os, 'setsid', None)
        if not setsid:
            setsid = getattr(os, 'setpgrp', None)
Tim Peters's avatar
Tim Peters committed
235

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        p = subprocess.Popen(cmdline, close_fds=True, stdin=inout,
                             stdout=(self.redirect_stdout and inout or None),
                             stderr=inout, preexec_fn=setsid)
        if remote:
            # wait five secons. If the subprocess is not finished, the
            # remote invocation has (hopefully) started a new instance.
            time.sleep(1)
            rc = p.poll()
            if rc is None:
                time.sleep(4)
                rc = p.poll()
                if rc is None:
                    return True
            # if remote call failed, open() will try direct invocation
            return not rc
        elif self.background:
            if p.poll() is None:
                return True
            else:
                return False
        else:
            return not p.wait()
Fred Drake's avatar
Fred Drake committed
258 259

    def open(self, url, new=0, autoraise=1):
260 261 262 263 264 265 266 267 268
        if new == 0:
            action = self.remote_action
        elif new == 1:
            action = self.remote_action_newwin
        elif new == 2:
            if self.remote_action_newtab is None:
                action = self.remote_action_newwin
            else:
                action = self.remote_action_newtab
Fred Drake's avatar
Fred Drake committed
269
        else:
270 271
            raise Error("Bad 'new' parameter to open(); " +
                        "expected 0, 1, or 2, got %s" % new)
Tim Peters's avatar
Tim Peters committed
272

273 274 275 276 277 278 279 280 281
        args = [arg.replace("%s", url).replace("%action", action)
                for arg in self.remote_args]
        success = self._invoke(args, True, autoraise)
        if not success:
            # remote invocation failed, try straight way
            args = [arg.replace("%s", url) for arg in self.args]
            return self._invoke(args, False, False)
        else:
            return True
Fred Drake's avatar
Fred Drake committed
282 283


284 285
class Mozilla(UnixBrowser):
    """Launcher class for Mozilla/Netscape browsers."""
Fred Drake's avatar
Fred Drake committed
286

287
    raise_opts = ["-noraise", "-raise"]
288

289 290 291 292
    remote_args = ['-remote', 'openURL(%s%action)']
    remote_action = ""
    remote_action_newwin = ",new-window"
    remote_action_newtab = ",new-tab"
Tim Peters's avatar
Tim Peters committed
293

294
    background = True
295

296
Netscape = Mozilla
297 298


299 300 301
class Galeon(UnixBrowser):
    """Launcher class for Galeon/Epiphany browsers."""

302 303 304 305
    raise_opts = ["-noraise", ""]
    remote_args = ['%action', '%s']
    remote_action = "-n"
    remote_action_newwin = "-w"
306

307
    background = True
308 309


310 311
class Opera(UnixBrowser):
    "Launcher class for Opera browser."
Fred Drake's avatar
Fred Drake committed
312

313
    raise_opts = ["", "-raise"]
Fred Drake's avatar
Fred Drake committed
314

315 316 317 318 319
    remote_args = ['-remote', 'openURL(%s%action)']
    remote_action = ""
    remote_action_newwin = ",new-window"
    remote_action_newtab = ",new-page"
    background = True
Fred Drake's avatar
Fred Drake committed
320

321

322 323
class Elinks(UnixBrowser):
    "Launcher class for Elinks browsers."
324

325 326 327 328 329
    remote_args = ['-remote', 'openURL(%s%action)']
    remote_action = ""
    remote_action_newwin = ",new-window"
    remote_action_newtab = ",new-tab"
    background = False
Fred Drake's avatar
Fred Drake committed
330

331 332 333
    # elinks doesn't like its stdout to be redirected -
    # it uses redirected stdout as a signal to do -dump
    redirect_stdout = False
Fred Drake's avatar
Fred Drake committed
334 335


336 337
class Konqueror(BaseBrowser):
    """Controller for the KDE File Manager (kfm, or Konqueror).
338

339 340 341
    See the output of ``kfmclient --commands``
    for more information on the Konqueror remote-control interface.
    """
342

343 344 345 346 347 348
    def open(self, url, new=0, autoraise=1):
        # XXX Currently I know no way to prevent KFM from opening a new win.
        if new == 2:
            action = "newTab"
        else:
            action = "openURL"
Tim Peters's avatar
Tim Peters committed
349

350 351 352 353 354 355
        devnull = file(os.devnull, "r+")
        # if possible, put browser in separate process group, so
        # keyboard interrupts don't affect browser as well as Python
        setsid = getattr(os, 'setsid', None)
        if not setsid:
            setsid = getattr(os, 'setpgrp', None)
Tim Peters's avatar
Tim Peters committed
356

357 358 359 360 361 362 363 364 365 366 367
        try:
            p = subprocess.Popen(["kfmclient", action, url],
                                 close_fds=True, stdin=devnull,
                                 stdout=devnull, stderr=devnull)
        except OSError:
            # fall through to next variant
            pass
        else:
            p.wait()
            # kfmclient's return code unfortunately has no meaning as it seems
            return True
368

369 370 371 372 373 374 375 376 377 378 379 380
        try:
            p = subprocess.Popen(["konqueror", "--silent", url],
                                 close_fds=True, stdin=devnull,
                                 stdout=devnull, stderr=devnull,
                                 preexec_fn=setsid)
        except OSError:
            # fall through to next variant
            pass
        else:
            if p.poll() is None:
                # Should be running now.
                return True
Tim Peters's avatar
Tim Peters committed
381

382 383 384 385 386 387 388 389 390
        try:
            p = subprocess.Popen(["kfm", "-d", url],
                                 close_fds=True, stdin=devnull,
                                 stdout=devnull, stderr=devnull,
                                 preexec_fn=setsid)
        except OSError:
            return False
        else:
            return (p.poll() is None)
391 392 393


class Grail(BaseBrowser):
Fred Drake's avatar
Fred Drake committed
394 395
    # There should be a way to maintain a connection to Grail, but the
    # Grail remote control protocol doesn't really allow that at this
396
    # point.  It probably never will!
Fred Drake's avatar
Fred Drake committed
397 398 399 400 401 402 403
    def _find_grail_rc(self):
        import glob
        import pwd
        import socket
        import tempfile
        tempdir = os.path.join(tempfile.gettempdir(),
                               ".grail-unix")
404
        user = pwd.getpwuid(os.getuid())[0]
Fred Drake's avatar
Fred Drake committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
        filename = os.path.join(tempdir, user + "-*")
        maybes = glob.glob(filename)
        if not maybes:
            return None
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        for fn in maybes:
            # need to PING each one until we find one that's live
            try:
                s.connect(fn)
            except socket.error:
                # no good; attempt to clean it out, but don't fail:
                try:
                    os.unlink(fn)
                except IOError:
                    pass
            else:
                return s

    def _remote(self, action):
        s = self._find_grail_rc()
        if not s:
            return 0
        s.send(action)
        s.close()
        return 1

    def open(self, url, new=0, autoraise=1):
        if new:
433
            ok = self._remote("LOADNEW " + url)
Fred Drake's avatar
Fred Drake committed
434
        else:
435 436
            ok = self._remote("LOAD " + url)
        return ok
Fred Drake's avatar
Fred Drake committed
437

438

Tim Peters's avatar
Tim Peters committed
439
#
440 441
# Platform support for Unix
#
442

443 444 445
# These are the right tests because all these Unix browsers require either
# a console terminal or an X display to run.

Neal Norwitz's avatar
Neal Norwitz committed
446
def register_X_browsers():
447 448 449 450 451 452 453 454 455 456

    # The default GNOME browser
    if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gnome-open"):
        register("gnome-open", None, BackgroundBrowser("gnome-open"))

    # The default KDE browser
    if "KDE_FULL_SESSION" in os.environ and _iscommand("kfmclient"):
        register("kfmclient", Konqueror, Konqueror("kfmclient"))

    # The Mozilla/Netscape browsers
457 458
    for browser in ("mozilla-firefox", "firefox",
                    "mozilla-firebird", "firebird",
459
                    "seamonkey", "mozilla", "netscape"):
460 461 462
        if _iscommand(browser):
            register(browser, None, Mozilla(browser))

463
    # Konqueror/kfm, the KDE browser.
464 465 466 467
    if _iscommand("kfm"):
        register("kfm", Konqueror, Konqueror("kfm"))
    elif _iscommand("konqueror"):
        register("konqueror", Konqueror, Konqueror("konqueror"))
468 469 470 471 472 473 474 475

    # Gnome's Galeon and Epiphany
    for browser in ("galeon", "epiphany"):
        if _iscommand(browser):
            register(browser, None, Galeon(browser))

    # Skipstone, another Gtk/Mozilla based browser
    if _iscommand("skipstone"):
476
        register("skipstone", None, BackgroundBrowser("skipstone"))
477 478 479 480 481 482 483

    # Opera, quite popular
    if _iscommand("opera"):
        register("opera", None, Opera("opera"))

    # Next, Mosaic -- old but still in use.
    if _iscommand("mosaic"):
484
        register("mosaic", None, BackgroundBrowser("mosaic"))
485 486 487 488 489

    # Grail, the Python browser. Does anybody still use it?
    if _iscommand("grail"):
        register("grail", Grail, None)

Neal Norwitz's avatar
Neal Norwitz committed
490 491 492 493
# Prefer X browsers if present
if os.environ.get("DISPLAY"):
    register_X_browsers()

494 495 496 497
# Also try console browsers
if os.environ.get("TERM"):
    # The Links/elinks browsers <http://artax.karlin.mff.cuni.cz/~mikulas/links/>
    if _iscommand("links"):
498
        register("links", None, GenericBrowser("links"))
499 500 501 502
    if _iscommand("elinks"):
        register("elinks", None, Elinks("elinks"))
    # The Lynx browser <http://lynx.isc.org/>, <http://lynx.browser.org/>
    if _iscommand("lynx"):
503
        register("lynx", None, GenericBrowser("lynx"))
504 505
    # The w3m browser <http://w3m.sourceforge.net/>
    if _iscommand("w3m"):
506
        register("w3m", None, GenericBrowser("w3m"))
Fred Drake's avatar
Fred Drake committed
507

508 509 510
#
# Platform support for Windows
#
511

512
if sys.platform[:3] == "win":
513 514
    class WindowsDefault(BaseBrowser):
        def open(self, url, new=0, autoraise=1):
515 516 517 518 519 520 521 522
            try:
                os.startfile(url)
            except WindowsError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True
523 524 525

    _tryorder = []
    _browsers = {}
526 527 528 529 530 531 532

    # First try to use the default Windows browser
    register("windows-default", WindowsDefault)

    # Detect some common Windows browsers, fallback to IE
    iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
                            "Internet Explorer\\IEXPLORE.EXE")
533
    for browser in ("firefox", "firebird", "seamonkey", "mozilla",
534
                    "netscape", "opera", iexplore):
535
        if _iscommand(browser):
536
            register(browser, None, BackgroundBrowser(browser))
537 538

#
539 540
# Platform support for MacOS
#
541 542 543 544 545 546

try:
    import ic
except ImportError:
    pass
else:
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    class InternetConfig(BaseBrowser):
        def open(self, url, new=0, autoraise=1):
            ic.launchurl(url)
            return True # Any way to get status?

    register("internet-config", InternetConfig, update_tryorder=-1)

if sys.platform == 'darwin':
    # Adapted from patch submitted to SourceForge by Steven J. Burr
    class MacOSX(BaseBrowser):
        """Launcher class for Aqua browsers on Mac OS X

        Optionally specify a browser name on instantiation.  Note that this
        will not work for Aqua browsers if the user has moved the application
        package after installation.

        If no browser is specified, the default browser, as specified in the
        Internet System Preferences panel, will be used.
        """
        def __init__(self, name):
            self.name = name

        def open(self, url, new=0, autoraise=1):
            assert "'" not in url
571 572 573
            # hack for local urls
            if not ':' in url:
                url = 'file:'+url
Tim Peters's avatar
Tim Peters committed
574

575 576 577 578
            # new must be 0 or 1
            new = int(bool(new))
            if self.name == "default":
                # User called open, open_new or get without a browser parameter
579
                script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
580 581 582 583 584 585 586 587
            else:
                # User called get and chose a browser
                if self.name == "OmniWeb":
                    toWindow = ""
                else:
                    # Include toWindow parameter of OpenURL command for browsers
                    # that support it.  0 == new window; -1 == existing
                    toWindow = "toWindow %d" % (new - 1)
588
                cmd = 'OpenURL "%s"' % url.replace('"', '%22')
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
                script = '''tell application "%s"
                                activate
                                %s %s
                            end tell''' % (self.name, cmd, toWindow)
            # Open pipe to AppleScript through osascript command
            osapipe = os.popen("osascript", "w")
            if osapipe is None:
                return False
            # Write script to osascript's stdin
            osapipe.write(script)
            rc = osapipe.close()
            return not rc

    # Don't clear _tryorder or _browsers since OS X can use above Unix support
    # (but we prefer using the OS X specific stuff)
    register("MacOSX", None, MacOSX('default'), -1)

606

607 608 609 610
#
# Platform support for OS/2
#

611 612 613
if sys.platform[:3] == "os2" and _iscommand("netscape"):
    _tryorder = []
    _browsers = {}
614
    register("os2netscape", None,
615
             GenericBrowser(["start", "netscape", "%s"]), -1)
616

617

618 619
# OK, now that we know what the default preference orders for each
# platform are, allow user to override them with the BROWSER variable.
620
if "BROWSER" in os.environ:
621 622 623 624 625 626 627 628 629 630 631 632
    _userchoices = os.environ["BROWSER"].split(os.pathsep)
    _userchoices.reverse()

    # Treat choices in same way as if passed into get() but do register
    # and prepend to _tryorder
    for cmdline in _userchoices:
        if cmdline != '':
            _synthesize(cmdline, -1)
    cmdline = None # to make del work if _userchoices was empty
    del cmdline
    del _userchoices

633
# what to do if _tryorder is now empty?
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657


def main():
    import getopt
    usage = """Usage: %s [-n | -t] url
    -n: open new window
    -t: open new tab""" % sys.argv[0]
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'ntd')
    except getopt.error, msg:
        print >>sys.stderr, msg
        print >>sys.stderr, usage
        sys.exit(1)
    new_win = 0
    for o, a in opts:
        if o == '-n': new_win = 1
        elif o == '-t': new_win = 2
    if len(args) <> 1:
        print >>sys.stderr, usage
        sys.exit(1)

    url = args[0]
    open(url, new_win)

658 659
    print "\a"

660 661
if __name__ == "__main__":
    main()