webbrowser.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. import threading
  10. import warnings
  11. __all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"]
  12. class Error(Exception):
  13. pass
  14. _lock = threading.RLock()
  15. _browsers = {} # Dictionary of available browser controllers
  16. _tryorder = None # Preference order of available browsers
  17. _os_preferred_browser = None # The preferred browser
  18. def register(name, klass, instance=None, *, preferred=False):
  19. """Register a browser connector."""
  20. with _lock:
  21. if _tryorder is None:
  22. register_standard_browsers()
  23. _browsers[name.lower()] = [klass, instance]
  24. # Preferred browsers go to the front of the list.
  25. # Need to match to the default browser returned by xdg-settings, which
  26. # may be of the form e.g. "firefox.desktop".
  27. if preferred or (_os_preferred_browser and f'{name}.desktop' == _os_preferred_browser):
  28. _tryorder.insert(0, name)
  29. else:
  30. _tryorder.append(name)
  31. def get(using=None):
  32. """Return a browser launcher instance appropriate for the environment."""
  33. if _tryorder is None:
  34. with _lock:
  35. if _tryorder is None:
  36. register_standard_browsers()
  37. if using is not None:
  38. alternatives = [using]
  39. else:
  40. alternatives = _tryorder
  41. for browser in alternatives:
  42. if '%s' in browser:
  43. # User gave us a command line, split it into name and args
  44. browser = shlex.split(browser)
  45. if browser[-1] == '&':
  46. return BackgroundBrowser(browser[:-1])
  47. else:
  48. return GenericBrowser(browser)
  49. else:
  50. # User gave us a browser name or path.
  51. try:
  52. command = _browsers[browser.lower()]
  53. except KeyError:
  54. command = _synthesize(browser)
  55. if command[1] is not None:
  56. return command[1]
  57. elif command[0] is not None:
  58. return command[0]()
  59. raise Error("could not locate runnable browser")
  60. # Please note: the following definition hides a builtin function.
  61. # It is recommended one does "import webbrowser" and uses webbrowser.open(url)
  62. # instead of "from webbrowser import *".
  63. def open(url, new=0, autoraise=True):
  64. """Display url using the default browser.
  65. If possible, open url in a location determined by new.
  66. - 0: the same browser window (the default).
  67. - 1: a new browser window.
  68. - 2: a new browser page ("tab").
  69. If possible, autoraise raises the window (the default) or not.
  70. If opening the browser succeeds, return True.
  71. If there is a problem, return False.
  72. """
  73. if _tryorder is None:
  74. with _lock:
  75. if _tryorder is None:
  76. register_standard_browsers()
  77. for name in _tryorder:
  78. browser = get(name)
  79. if browser.open(url, new, autoraise):
  80. return True
  81. return False
  82. def open_new(url):
  83. """Open url in a new window of the default browser.
  84. If not possible, then open url in the only browser window.
  85. """
  86. return open(url, 1)
  87. def open_new_tab(url):
  88. """Open url in a new page ("tab") of the default browser.
  89. If not possible, then the behavior becomes equivalent to open_new().
  90. """
  91. return open(url, 2)
  92. def _synthesize(browser, *, preferred=False):
  93. """Attempt to synthesize a controller based on existing controllers.
  94. This is useful to create a controller when a user specifies a path to
  95. an entry in the BROWSER environment variable -- we can copy a general
  96. controller to operate using a specific installation of the desired
  97. browser in this way.
  98. If we can't create a controller in this way, or if there is no
  99. executable for the requested browser, return [None, None].
  100. """
  101. cmd = browser.split()[0]
  102. if not shutil.which(cmd):
  103. return [None, None]
  104. name = os.path.basename(cmd)
  105. try:
  106. command = _browsers[name.lower()]
  107. except KeyError:
  108. return [None, None]
  109. # now attempt to clone to fit the new name:
  110. controller = command[1]
  111. if controller and name.lower() == controller.basename:
  112. import copy
  113. controller = copy.copy(controller)
  114. controller.name = browser
  115. controller.basename = os.path.basename(browser)
  116. register(browser, None, instance=controller, preferred=preferred)
  117. return [None, controller]
  118. return [None, None]
  119. # General parent classes
  120. class BaseBrowser(object):
  121. """Parent class for all browsers. Do not use directly."""
  122. args = ['%s']
  123. def __init__(self, name=""):
  124. self.name = name
  125. self.basename = name
  126. def open(self, url, new=0, autoraise=True):
  127. raise NotImplementedError
  128. def open_new(self, url):
  129. return self.open(url, 1)
  130. def open_new_tab(self, url):
  131. return self.open(url, 2)
  132. class GenericBrowser(BaseBrowser):
  133. """Class for all browsers started with a command
  134. and without remote functionality."""
  135. def __init__(self, name):
  136. if isinstance(name, str):
  137. self.name = name
  138. self.args = ["%s"]
  139. else:
  140. # name should be a list with arguments
  141. self.name = name[0]
  142. self.args = name[1:]
  143. self.basename = os.path.basename(self.name)
  144. def open(self, url, new=0, autoraise=True):
  145. sys.audit("webbrowser.open", url)
  146. cmdline = [self.name] + [arg.replace("%s", url)
  147. for arg in self.args]
  148. try:
  149. if sys.platform[:3] == 'win':
  150. p = subprocess.Popen(cmdline)
  151. else:
  152. p = subprocess.Popen(cmdline, close_fds=True)
  153. return not p.wait()
  154. except OSError:
  155. return False
  156. class BackgroundBrowser(GenericBrowser):
  157. """Class for all browsers which are to be started in the
  158. background."""
  159. def open(self, url, new=0, autoraise=True):
  160. cmdline = [self.name] + [arg.replace("%s", url)
  161. for arg in self.args]
  162. sys.audit("webbrowser.open", url)
  163. try:
  164. if sys.platform[:3] == 'win':
  165. p = subprocess.Popen(cmdline)
  166. else:
  167. p = subprocess.Popen(cmdline, close_fds=True,
  168. start_new_session=True)
  169. return (p.poll() is None)
  170. except OSError:
  171. return False
  172. class UnixBrowser(BaseBrowser):
  173. """Parent class for all Unix browsers with remote functionality."""
  174. raise_opts = None
  175. background = False
  176. redirect_stdout = True
  177. # In remote_args, %s will be replaced with the requested URL. %action will
  178. # be replaced depending on the value of 'new' passed to open.
  179. # remote_action is used for new=0 (open). If newwin is not None, it is
  180. # used for new=1 (open_new). If newtab is not None, it is used for
  181. # new=3 (open_new_tab). After both substitutions are made, any empty
  182. # strings in the transformed remote_args list will be removed.
  183. remote_args = ['%action', '%s']
  184. remote_action = None
  185. remote_action_newwin = None
  186. remote_action_newtab = None
  187. def _invoke(self, args, remote, autoraise, url=None):
  188. raise_opt = []
  189. if remote and self.raise_opts:
  190. # use autoraise argument only for remote invocation
  191. autoraise = int(autoraise)
  192. opt = self.raise_opts[autoraise]
  193. if opt: raise_opt = [opt]
  194. cmdline = [self.name] + raise_opt + args
  195. if remote or self.background:
  196. inout = subprocess.DEVNULL
  197. else:
  198. # for TTY browsers, we need stdin/out
  199. inout = None
  200. p = subprocess.Popen(cmdline, close_fds=True, stdin=inout,
  201. stdout=(self.redirect_stdout and inout or None),
  202. stderr=inout, start_new_session=True)
  203. if remote:
  204. # wait at most five seconds. If the subprocess is not finished, the
  205. # remote invocation has (hopefully) started a new instance.
  206. try:
  207. rc = p.wait(5)
  208. # if remote call failed, open() will try direct invocation
  209. return not rc
  210. except subprocess.TimeoutExpired:
  211. return True
  212. elif self.background:
  213. if p.poll() is None:
  214. return True
  215. else:
  216. return False
  217. else:
  218. return not p.wait()
  219. def open(self, url, new=0, autoraise=True):
  220. sys.audit("webbrowser.open", url)
  221. if new == 0:
  222. action = self.remote_action
  223. elif new == 1:
  224. action = self.remote_action_newwin
  225. elif new == 2:
  226. if self.remote_action_newtab is None:
  227. action = self.remote_action_newwin
  228. else:
  229. action = self.remote_action_newtab
  230. else:
  231. raise Error("Bad 'new' parameter to open(); " +
  232. "expected 0, 1, or 2, got %s" % new)
  233. args = [arg.replace("%s", url).replace("%action", action)
  234. for arg in self.remote_args]
  235. args = [arg for arg in args if arg]
  236. success = self._invoke(args, True, autoraise, url)
  237. if not success:
  238. # remote invocation failed, try straight way
  239. args = [arg.replace("%s", url) for arg in self.args]
  240. return self._invoke(args, False, False)
  241. else:
  242. return True
  243. class Mozilla(UnixBrowser):
  244. """Launcher class for Mozilla browsers."""
  245. remote_args = ['%action', '%s']
  246. remote_action = ""
  247. remote_action_newwin = "-new-window"
  248. remote_action_newtab = "-new-tab"
  249. background = True
  250. class Epiphany(UnixBrowser):
  251. """Launcher class for Epiphany browser."""
  252. raise_opts = ["-noraise", ""]
  253. remote_args = ['%action', '%s']
  254. remote_action = "-n"
  255. remote_action_newwin = "-w"
  256. background = True
  257. class Chrome(UnixBrowser):
  258. "Launcher class for Google Chrome browser."
  259. remote_args = ['%action', '%s']
  260. remote_action = ""
  261. remote_action_newwin = "--new-window"
  262. remote_action_newtab = ""
  263. background = True
  264. Chromium = Chrome
  265. class Opera(UnixBrowser):
  266. "Launcher class for Opera browser."
  267. remote_args = ['%action', '%s']
  268. remote_action = ""
  269. remote_action_newwin = "--new-window"
  270. remote_action_newtab = ""
  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. sys.audit("webbrowser.open", url)
  289. # XXX Currently I know no way to prevent KFM from opening a new win.
  290. if new == 2:
  291. action = "newTab"
  292. else:
  293. action = "openURL"
  294. devnull = subprocess.DEVNULL
  295. try:
  296. p = subprocess.Popen(["kfmclient", action, url],
  297. close_fds=True, stdin=devnull,
  298. stdout=devnull, stderr=devnull)
  299. except OSError:
  300. # fall through to next variant
  301. pass
  302. else:
  303. p.wait()
  304. # kfmclient's return code unfortunately has no meaning as it seems
  305. return True
  306. try:
  307. p = subprocess.Popen(["konqueror", "--silent", url],
  308. close_fds=True, stdin=devnull,
  309. stdout=devnull, stderr=devnull,
  310. start_new_session=True)
  311. except OSError:
  312. # fall through to next variant
  313. pass
  314. else:
  315. if p.poll() is None:
  316. # Should be running now.
  317. return True
  318. try:
  319. p = subprocess.Popen(["kfm", "-d", url],
  320. close_fds=True, stdin=devnull,
  321. stdout=devnull, stderr=devnull,
  322. start_new_session=True)
  323. except OSError:
  324. return False
  325. else:
  326. return (p.poll() is None)
  327. class Edge(UnixBrowser):
  328. "Launcher class for Microsoft Edge browser."
  329. remote_args = ['%action', '%s']
  330. remote_action = ""
  331. remote_action_newwin = "--new-window"
  332. remote_action_newtab = ""
  333. background = True
  334. #
  335. # Platform support for Unix
  336. #
  337. # These are the right tests because all these Unix browsers require either
  338. # a console terminal or an X display to run.
  339. def register_X_browsers():
  340. # use xdg-open if around
  341. if shutil.which("xdg-open"):
  342. register("xdg-open", None, BackgroundBrowser("xdg-open"))
  343. # Opens an appropriate browser for the URL scheme according to
  344. # freedesktop.org settings (GNOME, KDE, XFCE, etc.)
  345. if shutil.which("gio"):
  346. register("gio", None, BackgroundBrowser(["gio", "open", "--", "%s"]))
  347. # Equivalent of gio open before 2015
  348. if "GNOME_DESKTOP_SESSION_ID" in os.environ and shutil.which("gvfs-open"):
  349. register("gvfs-open", None, BackgroundBrowser("gvfs-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. # Common symbolic link for the default X11 browser
  354. if shutil.which("x-www-browser"):
  355. register("x-www-browser", None, BackgroundBrowser("x-www-browser"))
  356. # The Mozilla browsers
  357. for browser in ("firefox", "iceweasel", "seamonkey", "mozilla-firefox",
  358. "mozilla"):
  359. if shutil.which(browser):
  360. register(browser, None, Mozilla(browser))
  361. # Konqueror/kfm, the KDE browser.
  362. if shutil.which("kfm"):
  363. register("kfm", Konqueror, Konqueror("kfm"))
  364. elif shutil.which("konqueror"):
  365. register("konqueror", Konqueror, Konqueror("konqueror"))
  366. # Gnome's Epiphany
  367. if shutil.which("epiphany"):
  368. register("epiphany", None, Epiphany("epiphany"))
  369. # Google Chrome/Chromium browsers
  370. for browser in ("google-chrome", "chrome", "chromium", "chromium-browser"):
  371. if shutil.which(browser):
  372. register(browser, None, Chrome(browser))
  373. # Opera, quite popular
  374. if shutil.which("opera"):
  375. register("opera", None, Opera("opera"))
  376. if shutil.which("microsoft-edge"):
  377. register("microsoft-edge", None, Edge("microsoft-edge"))
  378. def register_standard_browsers():
  379. global _tryorder
  380. _tryorder = []
  381. if sys.platform == 'darwin':
  382. register("MacOSX", None, MacOSXOSAScript('default'))
  383. register("chrome", None, MacOSXOSAScript('chrome'))
  384. register("firefox", None, MacOSXOSAScript('firefox'))
  385. register("safari", None, MacOSXOSAScript('safari'))
  386. # OS X can use below Unix support (but we prefer using the OS X
  387. # specific stuff)
  388. if sys.platform == "serenityos":
  389. # SerenityOS webbrowser, simply called "Browser".
  390. register("Browser", None, BackgroundBrowser("Browser"))
  391. if sys.platform[:3] == "win":
  392. # First try to use the default Windows browser
  393. register("windows-default", WindowsDefault)
  394. # Detect some common Windows browsers, fallback to Microsoft Edge
  395. # location in 64-bit Windows
  396. edge64 = os.path.join(os.environ.get("PROGRAMFILES(x86)", "C:\\Program Files (x86)"),
  397. "Microsoft\\Edge\\Application\\msedge.exe")
  398. # location in 32-bit Windows
  399. edge32 = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
  400. "Microsoft\\Edge\\Application\\msedge.exe")
  401. for browser in ("firefox", "seamonkey", "mozilla", "chrome",
  402. "opera", edge64, edge32):
  403. if shutil.which(browser):
  404. register(browser, None, BackgroundBrowser(browser))
  405. if shutil.which("MicrosoftEdge.exe"):
  406. register("microsoft-edge", None, Edge("MicrosoftEdge.exe"))
  407. else:
  408. # Prefer X browsers if present
  409. if os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"):
  410. try:
  411. cmd = "xdg-settings get default-web-browser".split()
  412. raw_result = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
  413. result = raw_result.decode().strip()
  414. except (FileNotFoundError, subprocess.CalledProcessError, PermissionError, NotADirectoryError) :
  415. pass
  416. else:
  417. global _os_preferred_browser
  418. _os_preferred_browser = result
  419. register_X_browsers()
  420. # Also try console browsers
  421. if os.environ.get("TERM"):
  422. # Common symbolic link for the default text-based browser
  423. if shutil.which("www-browser"):
  424. register("www-browser", None, GenericBrowser("www-browser"))
  425. # The Links/elinks browsers <http://links.twibright.com/>
  426. if shutil.which("links"):
  427. register("links", None, GenericBrowser("links"))
  428. if shutil.which("elinks"):
  429. register("elinks", None, Elinks("elinks"))
  430. # The Lynx browser <https://lynx.invisible-island.net/>, <http://lynx.browser.org/>
  431. if shutil.which("lynx"):
  432. register("lynx", None, GenericBrowser("lynx"))
  433. # The w3m browser <http://w3m.sourceforge.net/>
  434. if shutil.which("w3m"):
  435. register("w3m", None, GenericBrowser("w3m"))
  436. # OK, now that we know what the default preference orders for each
  437. # platform are, allow user to override them with the BROWSER variable.
  438. if "BROWSER" in os.environ:
  439. userchoices = os.environ["BROWSER"].split(os.pathsep)
  440. userchoices.reverse()
  441. # Treat choices in same way as if passed into get() but do register
  442. # and prepend to _tryorder
  443. for cmdline in userchoices:
  444. if cmdline != '':
  445. cmd = _synthesize(cmdline, preferred=True)
  446. if cmd[1] is None:
  447. register(cmdline, None, GenericBrowser(cmdline), preferred=True)
  448. # what to do if _tryorder is now empty?
  449. #
  450. # Platform support for Windows
  451. #
  452. if sys.platform[:3] == "win":
  453. class WindowsDefault(BaseBrowser):
  454. def open(self, url, new=0, autoraise=True):
  455. sys.audit("webbrowser.open", url)
  456. try:
  457. os.startfile(url)
  458. except OSError:
  459. # [Error 22] No application is associated with the specified
  460. # file for this operation: '<URL>'
  461. return False
  462. else:
  463. return True
  464. #
  465. # Platform support for MacOS
  466. #
  467. if sys.platform == 'darwin':
  468. # Adapted from patch submitted to SourceForge by Steven J. Burr
  469. class MacOSX(BaseBrowser):
  470. """Launcher class for Aqua browsers on Mac OS X
  471. Optionally specify a browser name on instantiation. Note that this
  472. will not work for Aqua browsers if the user has moved the application
  473. package after installation.
  474. If no browser is specified, the default browser, as specified in the
  475. Internet System Preferences panel, will be used.
  476. """
  477. def __init__(self, name):
  478. warnings.warn(f'{self.__class__.__name__} is deprecated in 3.11'
  479. ' use MacOSXOSAScript instead.', DeprecationWarning, stacklevel=2)
  480. self.name = name
  481. def open(self, url, new=0, autoraise=True):
  482. sys.audit("webbrowser.open", url)
  483. assert "'" not in url
  484. # hack for local urls
  485. if not ':' in url:
  486. url = 'file:'+url
  487. # new must be 0 or 1
  488. new = int(bool(new))
  489. if self.name == "default":
  490. # User called open, open_new or get without a browser parameter
  491. script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
  492. else:
  493. # User called get and chose a browser
  494. if self.name == "OmniWeb":
  495. toWindow = ""
  496. else:
  497. # Include toWindow parameter of OpenURL command for browsers
  498. # that support it. 0 == new window; -1 == existing
  499. toWindow = "toWindow %d" % (new - 1)
  500. cmd = 'OpenURL "%s"' % url.replace('"', '%22')
  501. script = '''tell application "%s"
  502. activate
  503. %s %s
  504. end tell''' % (self.name, cmd, toWindow)
  505. # Open pipe to AppleScript through osascript command
  506. osapipe = os.popen("osascript", "w")
  507. if osapipe is None:
  508. return False
  509. # Write script to osascript's stdin
  510. osapipe.write(script)
  511. rc = osapipe.close()
  512. return not rc
  513. class MacOSXOSAScript(BaseBrowser):
  514. def __init__(self, name='default'):
  515. super().__init__(name)
  516. @property
  517. def _name(self):
  518. warnings.warn(f'{self.__class__.__name__}._name is deprecated in 3.11'
  519. f' use {self.__class__.__name__}.name instead.',
  520. DeprecationWarning, stacklevel=2)
  521. return self.name
  522. @_name.setter
  523. def _name(self, val):
  524. warnings.warn(f'{self.__class__.__name__}._name is deprecated in 3.11'
  525. f' use {self.__class__.__name__}.name instead.',
  526. DeprecationWarning, stacklevel=2)
  527. self.name = val
  528. def open(self, url, new=0, autoraise=True):
  529. sys.audit("webbrowser.open", url)
  530. if self.name == 'default':
  531. script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
  532. else:
  533. script = f'''
  534. tell application "%s"
  535. activate
  536. open location "%s"
  537. end
  538. '''%(self.name, url.replace('"', '%22'))
  539. osapipe = os.popen("osascript", "w")
  540. if osapipe is None:
  541. return False
  542. osapipe.write(script)
  543. rc = osapipe.close()
  544. return not rc
  545. def main():
  546. import getopt
  547. usage = """Usage: %s [-n | -t | -h] url
  548. -n: open new window
  549. -t: open new tab
  550. -h, --help: show help""" % sys.argv[0]
  551. try:
  552. opts, args = getopt.getopt(sys.argv[1:], 'ntdh',['help'])
  553. except getopt.error as msg:
  554. print(msg, file=sys.stderr)
  555. print(usage, file=sys.stderr)
  556. sys.exit(1)
  557. new_win = 0
  558. for o, a in opts:
  559. if o == '-n': new_win = 1
  560. elif o == '-t': new_win = 2
  561. elif o == '-h' or o == '--help':
  562. print(usage, file=sys.stderr)
  563. sys.exit()
  564. if len(args) != 1:
  565. print(usage, file=sys.stderr)
  566. sys.exit(1)
  567. url = args[0]
  568. open(url, new_win)
  569. print("\a")
  570. if __name__ == "__main__":
  571. main()