webbrowser.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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 Netscape(UnixBrowser):
  249. """Launcher class for Netscape browser."""
  250. raise_opts = ["-noraise", "-raise"]
  251. remote_args = ['-remote', 'openURL(%s%action)']
  252. remote_action = ""
  253. remote_action_newwin = ",new-window"
  254. remote_action_newtab = ",new-tab"
  255. background = True
  256. class Galeon(UnixBrowser):
  257. """Launcher class for Galeon/Epiphany browsers."""
  258. raise_opts = ["-noraise", ""]
  259. remote_args = ['%action', '%s']
  260. remote_action = "-n"
  261. remote_action_newwin = "-w"
  262. background = True
  263. class Chrome(UnixBrowser):
  264. "Launcher class for Google Chrome browser."
  265. remote_args = ['%action', '%s']
  266. remote_action = ""
  267. remote_action_newwin = "--new-window"
  268. remote_action_newtab = ""
  269. background = True
  270. Chromium = Chrome
  271. class Opera(UnixBrowser):
  272. "Launcher class for Opera browser."
  273. remote_args = ['%action', '%s']
  274. remote_action = ""
  275. remote_action_newwin = "--new-window"
  276. remote_action_newtab = ""
  277. background = True
  278. class Elinks(UnixBrowser):
  279. "Launcher class for Elinks browsers."
  280. remote_args = ['-remote', 'openURL(%s%action)']
  281. remote_action = ""
  282. remote_action_newwin = ",new-window"
  283. remote_action_newtab = ",new-tab"
  284. background = False
  285. # elinks doesn't like its stdout to be redirected -
  286. # it uses redirected stdout as a signal to do -dump
  287. redirect_stdout = False
  288. class Konqueror(BaseBrowser):
  289. """Controller for the KDE File Manager (kfm, or Konqueror).
  290. See the output of ``kfmclient --commands``
  291. for more information on the Konqueror remote-control interface.
  292. """
  293. def open(self, url, new=0, autoraise=True):
  294. sys.audit("webbrowser.open", url)
  295. # XXX Currently I know no way to prevent KFM from opening a new win.
  296. if new == 2:
  297. action = "newTab"
  298. else:
  299. action = "openURL"
  300. devnull = subprocess.DEVNULL
  301. try:
  302. p = subprocess.Popen(["kfmclient", action, url],
  303. close_fds=True, stdin=devnull,
  304. stdout=devnull, stderr=devnull)
  305. except OSError:
  306. # fall through to next variant
  307. pass
  308. else:
  309. p.wait()
  310. # kfmclient's return code unfortunately has no meaning as it seems
  311. return True
  312. try:
  313. p = subprocess.Popen(["konqueror", "--silent", url],
  314. close_fds=True, stdin=devnull,
  315. stdout=devnull, stderr=devnull,
  316. start_new_session=True)
  317. except OSError:
  318. # fall through to next variant
  319. pass
  320. else:
  321. if p.poll() is None:
  322. # Should be running now.
  323. return True
  324. try:
  325. p = subprocess.Popen(["kfm", "-d", url],
  326. close_fds=True, stdin=devnull,
  327. stdout=devnull, stderr=devnull,
  328. start_new_session=True)
  329. except OSError:
  330. return False
  331. else:
  332. return (p.poll() is None)
  333. class Grail(BaseBrowser):
  334. # There should be a way to maintain a connection to Grail, but the
  335. # Grail remote control protocol doesn't really allow that at this
  336. # point. It probably never will!
  337. def _find_grail_rc(self):
  338. import glob
  339. import pwd
  340. import socket
  341. import tempfile
  342. tempdir = os.path.join(tempfile.gettempdir(),
  343. ".grail-unix")
  344. user = pwd.getpwuid(os.getuid())[0]
  345. filename = os.path.join(glob.escape(tempdir), glob.escape(user) + "-*")
  346. maybes = glob.glob(filename)
  347. if not maybes:
  348. return None
  349. s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  350. for fn in maybes:
  351. # need to PING each one until we find one that's live
  352. try:
  353. s.connect(fn)
  354. except OSError:
  355. # no good; attempt to clean it out, but don't fail:
  356. try:
  357. os.unlink(fn)
  358. except OSError:
  359. pass
  360. else:
  361. return s
  362. def _remote(self, action):
  363. s = self._find_grail_rc()
  364. if not s:
  365. return 0
  366. s.send(action)
  367. s.close()
  368. return 1
  369. def open(self, url, new=0, autoraise=True):
  370. sys.audit("webbrowser.open", url)
  371. if new:
  372. ok = self._remote("LOADNEW " + url)
  373. else:
  374. ok = self._remote("LOAD " + url)
  375. return ok
  376. #
  377. # Platform support for Unix
  378. #
  379. # These are the right tests because all these Unix browsers require either
  380. # a console terminal or an X display to run.
  381. def register_X_browsers():
  382. # use xdg-open if around
  383. if shutil.which("xdg-open"):
  384. register("xdg-open", None, BackgroundBrowser("xdg-open"))
  385. # Opens an appropriate browser for the URL scheme according to
  386. # freedesktop.org settings (GNOME, KDE, XFCE, etc.)
  387. if shutil.which("gio"):
  388. register("gio", None, BackgroundBrowser(["gio", "open", "--", "%s"]))
  389. # Equivalent of gio open before 2015
  390. if "GNOME_DESKTOP_SESSION_ID" in os.environ and shutil.which("gvfs-open"):
  391. register("gvfs-open", None, BackgroundBrowser("gvfs-open"))
  392. # The default KDE browser
  393. if "KDE_FULL_SESSION" in os.environ and shutil.which("kfmclient"):
  394. register("kfmclient", Konqueror, Konqueror("kfmclient"))
  395. if shutil.which("x-www-browser"):
  396. register("x-www-browser", None, BackgroundBrowser("x-www-browser"))
  397. # The Mozilla browsers
  398. for browser in ("firefox", "iceweasel", "iceape", "seamonkey"):
  399. if shutil.which(browser):
  400. register(browser, None, Mozilla(browser))
  401. # The Netscape and old Mozilla browsers
  402. for browser in ("mozilla-firefox",
  403. "mozilla-firebird", "firebird",
  404. "mozilla", "netscape"):
  405. if shutil.which(browser):
  406. register(browser, None, Netscape(browser))
  407. # Konqueror/kfm, the KDE browser.
  408. if shutil.which("kfm"):
  409. register("kfm", Konqueror, Konqueror("kfm"))
  410. elif shutil.which("konqueror"):
  411. register("konqueror", Konqueror, Konqueror("konqueror"))
  412. # Gnome's Galeon and Epiphany
  413. for browser in ("galeon", "epiphany"):
  414. if shutil.which(browser):
  415. register(browser, None, Galeon(browser))
  416. # Skipstone, another Gtk/Mozilla based browser
  417. if shutil.which("skipstone"):
  418. register("skipstone", None, BackgroundBrowser("skipstone"))
  419. # Google Chrome/Chromium browsers
  420. for browser in ("google-chrome", "chrome", "chromium", "chromium-browser"):
  421. if shutil.which(browser):
  422. register(browser, None, Chrome(browser))
  423. # Opera, quite popular
  424. if shutil.which("opera"):
  425. register("opera", None, Opera("opera"))
  426. # Next, Mosaic -- old but still in use.
  427. if shutil.which("mosaic"):
  428. register("mosaic", None, BackgroundBrowser("mosaic"))
  429. # Grail, the Python browser. Does anybody still use it?
  430. if shutil.which("grail"):
  431. register("grail", Grail, None)
  432. def register_standard_browsers():
  433. global _tryorder
  434. _tryorder = []
  435. if sys.platform == 'darwin':
  436. register("MacOSX", None, MacOSXOSAScript('default'))
  437. register("chrome", None, MacOSXOSAScript('chrome'))
  438. register("firefox", None, MacOSXOSAScript('firefox'))
  439. register("safari", None, MacOSXOSAScript('safari'))
  440. # OS X can use below Unix support (but we prefer using the OS X
  441. # specific stuff)
  442. if sys.platform == "serenityos":
  443. # SerenityOS webbrowser, simply called "Browser".
  444. register("Browser", None, BackgroundBrowser("Browser"))
  445. if sys.platform[:3] == "win":
  446. # First try to use the default Windows browser
  447. register("windows-default", WindowsDefault)
  448. # Detect some common Windows browsers, fallback to IE
  449. iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
  450. "Internet Explorer\\IEXPLORE.EXE")
  451. for browser in ("firefox", "firebird", "seamonkey", "mozilla",
  452. "netscape", "opera", iexplore):
  453. if shutil.which(browser):
  454. register(browser, None, BackgroundBrowser(browser))
  455. else:
  456. # Prefer X browsers if present
  457. if os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"):
  458. try:
  459. cmd = "xdg-settings get default-web-browser".split()
  460. raw_result = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
  461. result = raw_result.decode().strip()
  462. except (FileNotFoundError, subprocess.CalledProcessError, PermissionError, NotADirectoryError) :
  463. pass
  464. else:
  465. global _os_preferred_browser
  466. _os_preferred_browser = result
  467. register_X_browsers()
  468. # Also try console browsers
  469. if os.environ.get("TERM"):
  470. if shutil.which("www-browser"):
  471. register("www-browser", None, GenericBrowser("www-browser"))
  472. # The Links/elinks browsers <http://artax.karlin.mff.cuni.cz/~mikulas/links/>
  473. if shutil.which("links"):
  474. register("links", None, GenericBrowser("links"))
  475. if shutil.which("elinks"):
  476. register("elinks", None, Elinks("elinks"))
  477. # The Lynx browser <http://lynx.isc.org/>, <http://lynx.browser.org/>
  478. if shutil.which("lynx"):
  479. register("lynx", None, GenericBrowser("lynx"))
  480. # The w3m browser <http://w3m.sourceforge.net/>
  481. if shutil.which("w3m"):
  482. register("w3m", None, GenericBrowser("w3m"))
  483. # OK, now that we know what the default preference orders for each
  484. # platform are, allow user to override them with the BROWSER variable.
  485. if "BROWSER" in os.environ:
  486. userchoices = os.environ["BROWSER"].split(os.pathsep)
  487. userchoices.reverse()
  488. # Treat choices in same way as if passed into get() but do register
  489. # and prepend to _tryorder
  490. for cmdline in userchoices:
  491. if cmdline != '':
  492. cmd = _synthesize(cmdline, preferred=True)
  493. if cmd[1] is None:
  494. register(cmdline, None, GenericBrowser(cmdline), preferred=True)
  495. # what to do if _tryorder is now empty?
  496. #
  497. # Platform support for Windows
  498. #
  499. if sys.platform[:3] == "win":
  500. class WindowsDefault(BaseBrowser):
  501. def open(self, url, new=0, autoraise=True):
  502. sys.audit("webbrowser.open", url)
  503. try:
  504. os.startfile(url)
  505. except OSError:
  506. # [Error 22] No application is associated with the specified
  507. # file for this operation: '<URL>'
  508. return False
  509. else:
  510. return True
  511. #
  512. # Platform support for MacOS
  513. #
  514. if sys.platform == 'darwin':
  515. # Adapted from patch submitted to SourceForge by Steven J. Burr
  516. class MacOSX(BaseBrowser):
  517. """Launcher class for Aqua browsers on Mac OS X
  518. Optionally specify a browser name on instantiation. Note that this
  519. will not work for Aqua browsers if the user has moved the application
  520. package after installation.
  521. If no browser is specified, the default browser, as specified in the
  522. Internet System Preferences panel, will be used.
  523. """
  524. def __init__(self, name):
  525. warnings.warn(f'{self.__class__.__name__} is deprecated in 3.11'
  526. ' use MacOSXOSAScript instead.', DeprecationWarning, stacklevel=2)
  527. self.name = name
  528. def open(self, url, new=0, autoraise=True):
  529. sys.audit("webbrowser.open", url)
  530. assert "'" not in url
  531. # hack for local urls
  532. if not ':' in url:
  533. url = 'file:'+url
  534. # new must be 0 or 1
  535. new = int(bool(new))
  536. if self.name == "default":
  537. # User called open, open_new or get without a browser parameter
  538. script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
  539. else:
  540. # User called get and chose a browser
  541. if self.name == "OmniWeb":
  542. toWindow = ""
  543. else:
  544. # Include toWindow parameter of OpenURL command for browsers
  545. # that support it. 0 == new window; -1 == existing
  546. toWindow = "toWindow %d" % (new - 1)
  547. cmd = 'OpenURL "%s"' % url.replace('"', '%22')
  548. script = '''tell application "%s"
  549. activate
  550. %s %s
  551. end tell''' % (self.name, cmd, toWindow)
  552. # Open pipe to AppleScript through osascript command
  553. osapipe = os.popen("osascript", "w")
  554. if osapipe is None:
  555. return False
  556. # Write script to osascript's stdin
  557. osapipe.write(script)
  558. rc = osapipe.close()
  559. return not rc
  560. class MacOSXOSAScript(BaseBrowser):
  561. def __init__(self, name='default'):
  562. super().__init__(name)
  563. @property
  564. def _name(self):
  565. warnings.warn(f'{self.__class__.__name__}._name is deprecated in 3.11'
  566. f' use {self.__class__.__name__}.name instead.',
  567. DeprecationWarning, stacklevel=2)
  568. return self.name
  569. @_name.setter
  570. def _name(self, val):
  571. warnings.warn(f'{self.__class__.__name__}._name is deprecated in 3.11'
  572. f' use {self.__class__.__name__}.name instead.',
  573. DeprecationWarning, stacklevel=2)
  574. self.name = val
  575. def open(self, url, new=0, autoraise=True):
  576. if self.name == 'default':
  577. script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
  578. else:
  579. script = f'''
  580. tell application "%s"
  581. activate
  582. open location "%s"
  583. end
  584. '''%(self.name, url.replace('"', '%22'))
  585. osapipe = os.popen("osascript", "w")
  586. if osapipe is None:
  587. return False
  588. osapipe.write(script)
  589. rc = osapipe.close()
  590. return not rc
  591. def main():
  592. import getopt
  593. usage = """Usage: %s [-n | -t] url
  594. -n: open new window
  595. -t: open new tab""" % sys.argv[0]
  596. try:
  597. opts, args = getopt.getopt(sys.argv[1:], 'ntd')
  598. except getopt.error as msg:
  599. print(msg, file=sys.stderr)
  600. print(usage, file=sys.stderr)
  601. sys.exit(1)
  602. new_win = 0
  603. for o, a in opts:
  604. if o == '-n': new_win = 1
  605. elif o == '-t': new_win = 2
  606. if len(args) != 1:
  607. print(usage, file=sys.stderr)
  608. sys.exit(1)
  609. url = args[0]
  610. open(url, new_win)
  611. print("\a")
  612. if __name__ == "__main__":
  613. main()