webbrowser.py 21 KB

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