webbrowser.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. #! /usr/bin/env python
  2. """Interfaces for launching and remotely controlling Web browsers."""
  3. # Maintained by Georg Brandl.
  4. import os
  5. import shlex
  6. import sys
  7. import stat
  8. import subprocess
  9. import time
  10. __all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"]
  11. class Error(Exception):
  12. pass
  13. _browsers = {} # Dictionary of available browser controllers
  14. _tryorder = [] # Preference order of available browsers
  15. def register(name, klass, instance=None, update_tryorder=1):
  16. """Register a browser connector and, optionally, connection."""
  17. _browsers[name.lower()] = [klass, instance]
  18. if update_tryorder > 0:
  19. _tryorder.append(name)
  20. elif update_tryorder < 0:
  21. _tryorder.insert(0, name)
  22. def get(using=None):
  23. """Return a browser launcher instance appropriate for the environment."""
  24. if using is not None:
  25. alternatives = [using]
  26. else:
  27. alternatives = _tryorder
  28. for browser in alternatives:
  29. if '%s' in browser:
  30. # User gave us a command line, split it into name and args
  31. browser = shlex.split(browser)
  32. if browser[-1] == '&':
  33. return BackgroundBrowser(browser[:-1])
  34. else:
  35. return GenericBrowser(browser)
  36. else:
  37. # User gave us a browser name or path.
  38. try:
  39. command = _browsers[browser.lower()]
  40. except KeyError:
  41. command = _synthesize(browser)
  42. if command[1] is not None:
  43. return command[1]
  44. elif command[0] is not None:
  45. return command[0]()
  46. raise Error("could not locate runnable browser")
  47. # Please note: the following definition hides a builtin function.
  48. # It is recommended one does "import webbrowser" and uses webbrowser.open(url)
  49. # instead of "from webbrowser import *".
  50. def open(url, new=0, autoraise=True):
  51. for name in _tryorder:
  52. browser = get(name)
  53. if browser.open(url, new, autoraise):
  54. return True
  55. return False
  56. def open_new(url):
  57. return open(url, 1)
  58. def open_new_tab(url):
  59. return open(url, 2)
  60. def _synthesize(browser, update_tryorder=1):
  61. """Attempt to synthesize a controller base on existing controllers.
  62. This is useful to create a controller when a user specifies a path to
  63. an entry in the BROWSER environment variable -- we can copy a general
  64. controller to operate using a specific installation of the desired
  65. browser in this way.
  66. If we can't create a controller in this way, or if there is no
  67. executable for the requested browser, return [None, None].
  68. """
  69. cmd = browser.split()[0]
  70. if not _iscommand(cmd):
  71. return [None, None]
  72. name = os.path.basename(cmd)
  73. try:
  74. command = _browsers[name.lower()]
  75. except KeyError:
  76. return [None, None]
  77. # now attempt to clone to fit the new name:
  78. controller = command[1]
  79. if controller and name.lower() == controller.basename:
  80. import copy
  81. controller = copy.copy(controller)
  82. controller.name = browser
  83. controller.basename = os.path.basename(browser)
  84. register(browser, None, controller, update_tryorder)
  85. return [None, controller]
  86. return [None, None]
  87. if sys.platform[:3] == "win":
  88. def _isexecutable(cmd):
  89. cmd = cmd.lower()
  90. if os.path.isfile(cmd) and cmd.endswith((".exe", ".bat")):
  91. return True
  92. for ext in ".exe", ".bat":
  93. if os.path.isfile(cmd + ext):
  94. return True
  95. return False
  96. else:
  97. def _isexecutable(cmd):
  98. if os.path.isfile(cmd):
  99. mode = os.stat(cmd)[stat.ST_MODE]
  100. if mode & stat.S_IXUSR or mode & stat.S_IXGRP or mode & stat.S_IXOTH:
  101. return True
  102. return False
  103. def _iscommand(cmd):
  104. """Return True if cmd is executable or can be found on the executable
  105. search path."""
  106. if _isexecutable(cmd):
  107. return True
  108. path = os.environ.get("PATH")
  109. if not path:
  110. return False
  111. for d in path.split(os.pathsep):
  112. exe = os.path.join(d, cmd)
  113. if _isexecutable(exe):
  114. return True
  115. return False
  116. # General parent classes
  117. class BaseBrowser(object):
  118. """Parent class for all browsers. Do not use directly."""
  119. args = ['%s']
  120. def __init__(self, name=""):
  121. self.name = name
  122. self.basename = name
  123. def open(self, url, new=0, autoraise=True):
  124. raise NotImplementedError
  125. def open_new(self, url):
  126. return self.open(url, 1)
  127. def open_new_tab(self, url):
  128. return self.open(url, 2)
  129. class GenericBrowser(BaseBrowser):
  130. """Class for all browsers started with a command
  131. and without remote functionality."""
  132. def __init__(self, name):
  133. if isinstance(name, basestring):
  134. self.name = name
  135. self.args = ["%s"]
  136. else:
  137. # name should be a list with arguments
  138. self.name = name[0]
  139. self.args = name[1:]
  140. self.basename = os.path.basename(self.name)
  141. def open(self, url, new=0, autoraise=True):
  142. cmdline = [self.name] + [arg.replace("%s", url)
  143. for arg in self.args]
  144. try:
  145. if sys.platform[:3] == 'win':
  146. p = subprocess.Popen(cmdline)
  147. else:
  148. p = subprocess.Popen(cmdline, close_fds=True)
  149. return not p.wait()
  150. except OSError:
  151. return False
  152. class BackgroundBrowser(GenericBrowser):
  153. """Class for all browsers which are to be started in the
  154. background."""
  155. def open(self, url, new=0, autoraise=True):
  156. cmdline = [self.name] + [arg.replace("%s", url)
  157. for arg in self.args]
  158. try:
  159. if sys.platform[:3] == 'win':
  160. p = subprocess.Popen(cmdline)
  161. else:
  162. setsid = getattr(os, 'setsid', None)
  163. if not setsid:
  164. setsid = getattr(os, 'setpgrp', None)
  165. p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid)
  166. return (p.poll() is None)
  167. except OSError:
  168. return False
  169. class UnixBrowser(BaseBrowser):
  170. """Parent class for all Unix browsers with remote functionality."""
  171. raise_opts = None
  172. remote_args = ['%action', '%s']
  173. remote_action = None
  174. remote_action_newwin = None
  175. remote_action_newtab = None
  176. background = False
  177. redirect_stdout = True
  178. def _invoke(self, args, remote, autoraise):
  179. raise_opt = []
  180. if remote and self.raise_opts:
  181. # use autoraise argument only for remote invocation
  182. autoraise = int(autoraise)
  183. opt = self.raise_opts[autoraise]
  184. if opt: raise_opt = [opt]
  185. cmdline = [self.name] + raise_opt + args
  186. if remote or self.background:
  187. inout = file(os.devnull, "r+")
  188. else:
  189. # for TTY browsers, we need stdin/out
  190. inout = None
  191. # if possible, put browser in separate process group, so
  192. # keyboard interrupts don't affect browser as well as Python
  193. setsid = getattr(os, 'setsid', None)
  194. if not setsid:
  195. setsid = getattr(os, 'setpgrp', None)
  196. p = subprocess.Popen(cmdline, close_fds=True, stdin=inout,
  197. stdout=(self.redirect_stdout and inout or None),
  198. stderr=inout, preexec_fn=setsid)
  199. if remote:
  200. # wait five seconds. If the subprocess is not finished, the
  201. # remote invocation has (hopefully) started a new instance.
  202. time.sleep(1)
  203. rc = p.poll()
  204. if rc is None:
  205. time.sleep(4)
  206. rc = p.poll()
  207. if rc is None:
  208. return True
  209. # if remote call failed, open() will try direct invocation
  210. return not rc
  211. elif self.background:
  212. if p.poll() is None:
  213. return True
  214. else:
  215. return False
  216. else:
  217. return not p.wait()
  218. def open(self, url, new=0, autoraise=True):
  219. if new == 0:
  220. action = self.remote_action
  221. elif new == 1:
  222. action = self.remote_action_newwin
  223. elif new == 2:
  224. if self.remote_action_newtab is None:
  225. action = self.remote_action_newwin
  226. else:
  227. action = self.remote_action_newtab
  228. else:
  229. raise Error("Bad 'new' parameter to open(); " +
  230. "expected 0, 1, or 2, got %s" % new)
  231. args = [arg.replace("%s", url).replace("%action", action)
  232. for arg in self.remote_args]
  233. success = self._invoke(args, True, autoraise)
  234. if not success:
  235. # remote invocation failed, try straight way
  236. args = [arg.replace("%s", url) for arg in self.args]
  237. return self._invoke(args, False, False)
  238. else:
  239. return True
  240. class Mozilla(UnixBrowser):
  241. """Launcher class for Mozilla/Netscape browsers."""
  242. raise_opts = ["-noraise", "-raise"]
  243. remote_args = ['-remote', 'openURL(%s%action)']
  244. remote_action = ""
  245. remote_action_newwin = ",new-window"
  246. remote_action_newtab = ",new-tab"
  247. background = True
  248. Netscape = Mozilla
  249. class Galeon(UnixBrowser):
  250. """Launcher class for Galeon/Epiphany browsers."""
  251. raise_opts = ["-noraise", ""]
  252. remote_args = ['%action', '%s']
  253. remote_action = "-n"
  254. remote_action_newwin = "-w"
  255. background = True
  256. class Chrome(UnixBrowser):
  257. "Launcher class for Google Chrome browser."
  258. remote_args = ['%action', '%s']
  259. remote_action = ""
  260. remote_action_newwin = "--new-window"
  261. remote_action_newtab = ""
  262. background = True
  263. Chromium = Chrome
  264. class Opera(UnixBrowser):
  265. "Launcher class for Opera browser."
  266. raise_opts = ["-noraise", ""]
  267. remote_args = ['-remote', 'openURL(%s%action)']
  268. remote_action = ""
  269. remote_action_newwin = ",new-window"
  270. remote_action_newtab = ",new-page"
  271. background = True
  272. class Elinks(UnixBrowser):
  273. "Launcher class for Elinks browsers."
  274. remote_args = ['-remote', 'openURL(%s%action)']
  275. remote_action = ""
  276. remote_action_newwin = ",new-window"
  277. remote_action_newtab = ",new-tab"
  278. background = False
  279. # elinks doesn't like its stdout to be redirected -
  280. # it uses redirected stdout as a signal to do -dump
  281. redirect_stdout = False
  282. class Konqueror(BaseBrowser):
  283. """Controller for the KDE File Manager (kfm, or Konqueror).
  284. See the output of ``kfmclient --commands``
  285. for more information on the Konqueror remote-control interface.
  286. """
  287. def open(self, url, new=0, autoraise=True):
  288. # XXX Currently I know no way to prevent KFM from opening a new win.
  289. if new == 2:
  290. action = "newTab"
  291. else:
  292. action = "openURL"
  293. devnull = file(os.devnull, "r+")
  294. # if possible, put browser in separate process group, so
  295. # keyboard interrupts don't affect browser as well as Python
  296. setsid = getattr(os, 'setsid', None)
  297. if not setsid:
  298. setsid = getattr(os, 'setpgrp', None)
  299. try:
  300. p = subprocess.Popen(["kfmclient", action, url],
  301. close_fds=True, stdin=devnull,
  302. stdout=devnull, stderr=devnull)
  303. except OSError:
  304. # fall through to next variant
  305. pass
  306. else:
  307. p.wait()
  308. # kfmclient's return code unfortunately has no meaning as it seems
  309. return True
  310. try:
  311. p = subprocess.Popen(["konqueror", "--silent", url],
  312. close_fds=True, stdin=devnull,
  313. stdout=devnull, stderr=devnull,
  314. preexec_fn=setsid)
  315. except OSError:
  316. # fall through to next variant
  317. pass
  318. else:
  319. if p.poll() is None:
  320. # Should be running now.
  321. return True
  322. try:
  323. p = subprocess.Popen(["kfm", "-d", url],
  324. close_fds=True, stdin=devnull,
  325. stdout=devnull, stderr=devnull,
  326. preexec_fn=setsid)
  327. except OSError:
  328. return False
  329. else:
  330. return (p.poll() is None)
  331. class Grail(BaseBrowser):
  332. # There should be a way to maintain a connection to Grail, but the
  333. # Grail remote control protocol doesn't really allow that at this
  334. # point. It probably never will!
  335. def _find_grail_rc(self):
  336. import glob
  337. import pwd
  338. import socket
  339. import tempfile
  340. tempdir = os.path.join(tempfile.gettempdir(),
  341. ".grail-unix")
  342. user = pwd.getpwuid(os.getuid())[0]
  343. filename = os.path.join(tempdir, user + "-*")
  344. maybes = glob.glob(filename)
  345. if not maybes:
  346. return None
  347. s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  348. for fn in maybes:
  349. # need to PING each one until we find one that's live
  350. try:
  351. s.connect(fn)
  352. except socket.error:
  353. # no good; attempt to clean it out, but don't fail:
  354. try:
  355. os.unlink(fn)
  356. except IOError:
  357. pass
  358. else:
  359. return s
  360. def _remote(self, action):
  361. s = self._find_grail_rc()
  362. if not s:
  363. return 0
  364. s.send(action)
  365. s.close()
  366. return 1
  367. def open(self, url, new=0, autoraise=True):
  368. if new:
  369. ok = self._remote("LOADNEW " + url)
  370. else:
  371. ok = self._remote("LOAD " + url)
  372. return ok
  373. #
  374. # Platform support for Unix
  375. #
  376. # These are the right tests because all these Unix browsers require either
  377. # a console terminal or an X display to run.
  378. def register_X_browsers():
  379. # use xdg-open if around
  380. if _iscommand("xdg-open"):
  381. register("xdg-open", None, BackgroundBrowser("xdg-open"))
  382. # The default GNOME3 browser
  383. if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gvfs-open"):
  384. register("gvfs-open", None, BackgroundBrowser("gvfs-open"))
  385. # The default GNOME browser
  386. if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gnome-open"):
  387. register("gnome-open", None, BackgroundBrowser("gnome-open"))
  388. # The default KDE browser
  389. if "KDE_FULL_SESSION" in os.environ and _iscommand("kfmclient"):
  390. register("kfmclient", Konqueror, Konqueror("kfmclient"))
  391. if _iscommand("x-www-browser"):
  392. register("x-www-browser", None, BackgroundBrowser("x-www-browser"))
  393. # The Mozilla/Netscape browsers
  394. for browser in ("mozilla-firefox", "firefox",
  395. "mozilla-firebird", "firebird",
  396. "iceweasel", "iceape",
  397. "seamonkey", "mozilla", "netscape"):
  398. if _iscommand(browser):
  399. register(browser, None, Mozilla(browser))
  400. # Konqueror/kfm, the KDE browser.
  401. if _iscommand("kfm"):
  402. register("kfm", Konqueror, Konqueror("kfm"))
  403. elif _iscommand("konqueror"):
  404. register("konqueror", Konqueror, Konqueror("konqueror"))
  405. # Gnome's Galeon and Epiphany
  406. for browser in ("galeon", "epiphany"):
  407. if _iscommand(browser):
  408. register(browser, None, Galeon(browser))
  409. # Skipstone, another Gtk/Mozilla based browser
  410. if _iscommand("skipstone"):
  411. register("skipstone", None, BackgroundBrowser("skipstone"))
  412. # Google Chrome/Chromium browsers
  413. for browser in ("google-chrome", "chrome", "chromium", "chromium-browser"):
  414. if _iscommand(browser):
  415. register(browser, None, Chrome(browser))
  416. # Opera, quite popular
  417. if _iscommand("opera"):
  418. register("opera", None, Opera("opera"))
  419. # Next, Mosaic -- old but still in use.
  420. if _iscommand("mosaic"):
  421. register("mosaic", None, BackgroundBrowser("mosaic"))
  422. # Grail, the Python browser. Does anybody still use it?
  423. if _iscommand("grail"):
  424. register("grail", Grail, None)
  425. # Prefer X browsers if present
  426. if os.environ.get("DISPLAY"):
  427. register_X_browsers()
  428. # Also try console browsers
  429. if os.environ.get("TERM"):
  430. if _iscommand("www-browser"):
  431. register("www-browser", None, GenericBrowser("www-browser"))
  432. # The Links/elinks browsers <http://artax.karlin.mff.cuni.cz/~mikulas/links/>
  433. if _iscommand("links"):
  434. register("links", None, GenericBrowser("links"))
  435. if _iscommand("elinks"):
  436. register("elinks", None, Elinks("elinks"))
  437. # The Lynx browser <http://lynx.isc.org/>, <http://lynx.browser.org/>
  438. if _iscommand("lynx"):
  439. register("lynx", None, GenericBrowser("lynx"))
  440. # The w3m browser <http://w3m.sourceforge.net/>
  441. if _iscommand("w3m"):
  442. register("w3m", None, GenericBrowser("w3m"))
  443. #
  444. # Platform support for Windows
  445. #
  446. if sys.platform[:3] == "win":
  447. class WindowsDefault(BaseBrowser):
  448. def open(self, url, new=0, autoraise=True):
  449. try:
  450. os.startfile(url)
  451. except WindowsError:
  452. # [Error 22] No application is associated with the specified
  453. # file for this operation: '<URL>'
  454. return False
  455. else:
  456. return True
  457. _tryorder = []
  458. _browsers = {}
  459. # First try to use the default Windows browser
  460. register("windows-default", WindowsDefault)
  461. # Detect some common Windows browsers, fallback to IE
  462. iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
  463. "Internet Explorer\\IEXPLORE.EXE")
  464. for browser in ("firefox", "firebird", "seamonkey", "mozilla",
  465. "netscape", "opera", iexplore):
  466. if _iscommand(browser):
  467. register(browser, None, BackgroundBrowser(browser))
  468. #
  469. # Platform support for MacOS
  470. #
  471. if sys.platform == 'darwin':
  472. # Adapted from patch submitted to SourceForge by Steven J. Burr
  473. class MacOSX(BaseBrowser):
  474. """Launcher class for Aqua browsers on Mac OS X
  475. Optionally specify a browser name on instantiation. Note that this
  476. will not work for Aqua browsers if the user has moved the application
  477. package after installation.
  478. If no browser is specified, the default browser, as specified in the
  479. Internet System Preferences panel, will be used.
  480. """
  481. def __init__(self, name):
  482. self.name = name
  483. def open(self, url, new=0, autoraise=True):
  484. assert "'" not in url
  485. # hack for local urls
  486. if not ':' in url:
  487. url = 'file:'+url
  488. # new must be 0 or 1
  489. new = int(bool(new))
  490. if self.name == "default":
  491. # User called open, open_new or get without a browser parameter
  492. script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
  493. else:
  494. # User called get and chose a browser
  495. if self.name == "OmniWeb":
  496. toWindow = ""
  497. else:
  498. # Include toWindow parameter of OpenURL command for browsers
  499. # that support it. 0 == new window; -1 == existing
  500. toWindow = "toWindow %d" % (new - 1)
  501. cmd = 'OpenURL "%s"' % url.replace('"', '%22')
  502. script = '''tell application "%s"
  503. activate
  504. %s %s
  505. end tell''' % (self.name, cmd, toWindow)
  506. # Open pipe to AppleScript through osascript command
  507. osapipe = os.popen("osascript", "w")
  508. if osapipe is None:
  509. return False
  510. # Write script to osascript's stdin
  511. osapipe.write(script)
  512. rc = osapipe.close()
  513. return not rc
  514. class MacOSXOSAScript(BaseBrowser):
  515. def __init__(self, name):
  516. self._name = name
  517. def open(self, url, new=0, autoraise=True):
  518. if self._name == 'default':
  519. script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
  520. else:
  521. script = '''
  522. tell application "%s"
  523. activate
  524. open location "%s"
  525. end
  526. '''%(self._name, url.replace('"', '%22'))
  527. osapipe = os.popen("osascript", "w")
  528. if osapipe is None:
  529. return False
  530. osapipe.write(script)
  531. rc = osapipe.close()
  532. return not rc
  533. # Don't clear _tryorder or _browsers since OS X can use above Unix support
  534. # (but we prefer using the OS X specific stuff)
  535. register("safari", None, MacOSXOSAScript('safari'), -1)
  536. register("firefox", None, MacOSXOSAScript('firefox'), -1)
  537. register("MacOSX", None, MacOSXOSAScript('default'), -1)
  538. #
  539. # Platform support for OS/2
  540. #
  541. if sys.platform[:3] == "os2" and _iscommand("netscape"):
  542. _tryorder = []
  543. _browsers = {}
  544. register("os2netscape", None,
  545. GenericBrowser(["start", "netscape", "%s"]), -1)
  546. # OK, now that we know what the default preference orders for each
  547. # platform are, allow user to override them with the BROWSER variable.
  548. if "BROWSER" in os.environ:
  549. _userchoices = os.environ["BROWSER"].split(os.pathsep)
  550. _userchoices.reverse()
  551. # Treat choices in same way as if passed into get() but do register
  552. # and prepend to _tryorder
  553. for cmdline in _userchoices:
  554. if cmdline != '':
  555. cmd = _synthesize(cmdline, -1)
  556. if cmd[1] is None:
  557. register(cmdline, None, GenericBrowser(cmdline), -1)
  558. cmdline = None # to make del work if _userchoices was empty
  559. del cmdline
  560. del _userchoices
  561. # what to do if _tryorder is now empty?
  562. def main():
  563. import getopt
  564. usage = """Usage: %s [-n | -t] url
  565. -n: open new window
  566. -t: open new tab""" % sys.argv[0]
  567. try:
  568. opts, args = getopt.getopt(sys.argv[1:], 'ntd')
  569. except getopt.error, msg:
  570. print >>sys.stderr, msg
  571. print >>sys.stderr, usage
  572. sys.exit(1)
  573. new_win = 0
  574. for o, a in opts:
  575. if o == '-n': new_win = 1
  576. elif o == '-t': new_win = 2
  577. if len(args) != 1:
  578. print >>sys.stderr, usage
  579. sys.exit(1)
  580. url = args[0]
  581. open(url, new_win)
  582. print "\a"
  583. if __name__ == "__main__":
  584. main()