webbrowser.py 23 KB

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