Debian Codegraph @

lib-python/3/webbrowser.py

raw symbols ◀ ▶ SCIP
3 Debian patches touch this file
1 #! /usr/bin/env python3
2 """Interfaces for launching and remotely controlling web browsers."""
3 # Maintained by Georg Brandl.
4
5 import os
6 import shlex
7 import shutil
8 import sys
9 import subprocess
10 import threading
11 import warnings
12
13 __all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"]
14
15 class Error(Exception):
16 pass
17
18 _lock = threading.RLock()
19 _browsers = {} # Dictionary of available browser controllers
20 _tryorder = None # Preference order of available browsers
21 _os_preferred_browser = None # The preferred browser
22
23 def register(name, klass, instance=None, *, preferred=False):
24 """Register a browser connector."""
25 with _lock:
26 if _tryorder is None:
27 register_standard_browsers()
28 _browsers[name.lower()] = [klass, instance]
29
30 # Preferred browsers go to the front of the list.
31 # Need to match to the default browser returned by xdg-settings, which
32 # may be of the form e.g. "firefox.desktop".
33 if preferred or (_os_preferred_browser and name in _os_preferred_browser):
34 _tryorder.insert(0, name)
35 else:
36 _tryorder.append(name)
37
38 def get(using=None):
39 """Return a browser launcher instance appropriate for the environment."""
40 if _tryorder is None:
41 with _lock:
42 if _tryorder is None:
43 register_standard_browsers()
44 if using is not None:
45 alternatives = [using]
46 else:
47 alternatives = _tryorder
48 for browser in alternatives:
49 if '%s' in browser:
50 # User gave us a command line, split it into name and args
51 browser = shlex.split(browser)
52 if browser[-1] == '&':
53 return BackgroundBrowser(browser[:-1])
54 else:
55 return GenericBrowser(browser)
56 else:
57 # User gave us a browser name or path.
58 try:
59 command = _browsers[browser.lower()]
60 except KeyError:
61 command = _synthesize(browser)
62 if command[1] is not None:
63 return command[1]
64 elif command[0] is not None:
65 return command[0]()
66 raise Error("could not locate runnable browser")
67
68 # Please note: the following definition hides a builtin function.
69 # It is recommended one does "import webbrowser" and uses webbrowser.open(url)
70 # instead of "from webbrowser import *".
71
72 def open(url, new=0, autoraise=True):
73 """Display url using the default browser.
74
75 If possible, open url in a location determined by new.
76 - 0: the same browser window (the default).
77 - 1: a new browser window.
78 - 2: a new browser page ("tab").
79 If possible, autoraise raises the window (the default) or not.
80 """
81 if _tryorder is None:
82 with _lock:
83 if _tryorder is None:
84 register_standard_browsers()
85 for name in _tryorder:
86 browser = get(name)
87 if browser.open(url, new, autoraise):
88 return True
89 return False
90
91 def open_new(url):
92 """Open url in a new window of the default browser.
93
94 If not possible, then open url in the only browser window.
95 """
96 return open(url, 1)
97
98 def open_new_tab(url):
99 """Open url in a new page ("tab") of the default browser.
100
101 If not possible, then the behavior becomes equivalent to open_new().
102 """
103 return open(url, 2)
104
105
106 def _synthesize(browser, *, preferred=False):
107 """Attempt to synthesize a controller based on existing controllers.
108
109 This is useful to create a controller when a user specifies a path to
110 an entry in the BROWSER environment variable -- we can copy a general
111 controller to operate using a specific installation of the desired
112 browser in this way.
113
114 If we can't create a controller in this way, or if there is no
115 executable for the requested browser, return [None, None].
116
117 """
118 cmd = browser.split()[0]
119 if not shutil.which(cmd):
120 return [None, None]
121 name = os.path.basename(cmd)
122 try:
123 command = _browsers[name.lower()]
124 except KeyError:
125 return [None, None]
126 # now attempt to clone to fit the new name:
127 controller = command[1]
128 if controller and name.lower() == controller.basename:
129 import copy
130 controller = copy.copy(controller)
131 controller.name = browser
132 controller.basename = os.path.basename(browser)
133 register(browser, None, instance=controller, preferred=preferred)
134 return [None, controller]
135 return [None, None]
136
137
138 # General parent classes
139
140 class BaseBrowser(object):
141 """Parent class for all browsers. Do not use directly."""
142
143 args = ['%s']
144
145 def __init__(self, name=""):
146 self.name = name
147 self.basename = name
148
149 def open(self, url, new=0, autoraise=True):
150 raise NotImplementedError
151
152 def open_new(self, url):
153 return self.open(url, 1)
154
155 def open_new_tab(self, url):
156 return self.open(url, 2)
157
•158 @staticmethod
159 def _check_url(url):
160 """Ensures that the URL is safe to pass to subprocesses as a parameter"""
161 if url and url.lstrip().startswith("-"):
•162 raise ValueError(f"Invalid URL (leading dash disallowed): {url!r}")
163
164
165 class GenericBrowser(BaseBrowser):
166 """Class for all browsers started with a command
167 and without remote functionality."""
168
169 def __init__(self, name):
170 if isinstance(name, str):
171 self.name = name
172 self.args = ["%s"]
173 else:
174 # name should be a list with arguments
175 self.name = name[0]
176 self.args = name[1:]
177 self.basename = os.path.basename(self.name)
178
179 def open(self, url, new=0, autoraise=True):
180 sys.audit("webbrowser.open", url)
•181 self._check_url(url)
182 cmdline = [self.name] + [arg.replace("%s", url)
183 for arg in self.args]
184 try:
185 if sys.platform[:3] == 'win':
186 p = subprocess.Popen(cmdline)
187 else:
188 p = subprocess.Popen(cmdline, close_fds=True)
189 return not p.wait()
190 except OSError:
191 return False
192
193
194 class BackgroundBrowser(GenericBrowser):
195 """Class for all browsers which are to be started in the
196 background."""
197
198 def open(self, url, new=0, autoraise=True):
199 cmdline = [self.name] + [arg.replace("%s", url)
200 for arg in self.args]
201 sys.audit("webbrowser.open", url)
•202 self._check_url(url)
203 try:
204 if sys.platform[:3] == 'win':
205 p = subprocess.Popen(cmdline)
206 else:
207 p = subprocess.Popen(cmdline, close_fds=True,
208 start_new_session=True)
209 return (p.poll() is None)
210 except OSError:
211 return False
212
213
214 class UnixBrowser(BaseBrowser):
215 """Parent class for all Unix browsers with remote functionality."""
216
217 raise_opts = None
218 background = False
219 redirect_stdout = True
220 # In remote_args, %s will be replaced with the requested URL. %action will
221 # be replaced depending on the value of 'new' passed to open.
222 # remote_action is used for new=0 (open). If newwin is not None, it is
223 # used for new=1 (open_new). If newtab is not None, it is used for
224 # new=3 (open_new_tab). After both substitutions are made, any empty
225 # strings in the transformed remote_args list will be removed.
226 remote_args = ['%action', '%s']
227 remote_action = None
228 remote_action_newwin = None
229 remote_action_newtab = None
230
231 def _invoke(self, args, remote, autoraise, url=None):
232 raise_opt = []
233 if remote and self.raise_opts:
234 # use autoraise argument only for remote invocation
235 autoraise = int(autoraise)
236 opt = self.raise_opts[autoraise]
237 if opt: raise_opt = [opt]
238
239 cmdline = [self.name] + raise_opt + args
240
241 if remote or self.background:
242 inout = subprocess.DEVNULL
243 else:
244 # for TTY browsers, we need stdin/out
245 inout = None
246 p = subprocess.Popen(cmdline, close_fds=True, stdin=inout,
247 stdout=(self.redirect_stdout and inout or None),
248 stderr=inout, start_new_session=True)
249 if remote:
250 # wait at most five seconds. If the subprocess is not finished, the
251 # remote invocation has (hopefully) started a new instance.
252 try:
253 rc = p.wait(5)
254 # if remote call failed, open() will try direct invocation
255 return not rc
256 except subprocess.TimeoutExpired:
257 return True
258 elif self.background:
259 if p.poll() is None:
260 return True
261 else:
262 return False
263 else:
264 return not p.wait()
265
266 def open(self, url, new=0, autoraise=True):
267 sys.audit("webbrowser.open", url)
•268 if new == 0:
269 action = self.remote_action
270 elif new == 1:
271 action = self.remote_action_newwin
272 elif new == 2:
273 if self.remote_action_newtab is None:
274 action = self.remote_action_newwin
275 else:
276 action = self.remote_action_newtab
277 else:
278 raise Error("Bad 'new' parameter to open(); " +
279 "expected 0, 1, or 2, got %s" % new)
280
•281 self._check_url(url.replace("%action", action))
282
283 args = [arg.replace("%action", action).replace("%s", url)
284 for arg in self.remote_args]
285 args = [arg for arg in args if arg]
286 success = self._invoke(args, True, autoraise, url)
287 if not success:
288 # remote invocation failed, try straight way
289 args = [arg.replace("%s", url) for arg in self.args]
290 return self._invoke(args, False, False)
291 else:
292 return True
293
294
295 class Mozilla(UnixBrowser):
296 """Launcher class for Mozilla browsers."""
297
298 remote_args = ['%action', '%s']
299 remote_action = ""
300 remote_action_newwin = "-new-window"
301 remote_action_newtab = "-new-tab"
302 background = True
303
304
305 class Netscape(UnixBrowser):
306 """Launcher class for Netscape browser."""
307
308 raise_opts = ["-noraise", "-raise"]
309 remote_args = ['-remote', 'openURL(%s%action)']
310 remote_action = ""
311 remote_action_newwin = ",new-window"
312 remote_action_newtab = ",new-tab"
313 background = True
314
315
316 class Galeon(UnixBrowser):
317 """Launcher class for Galeon/Epiphany browsers."""
318
319 raise_opts = ["-noraise", ""]
320 remote_args = ['%action', '%s']
321 remote_action = "-n"
322 remote_action_newwin = "-w"
323 background = True
324
325
326 class Chrome(UnixBrowser):
327 "Launcher class for Google Chrome browser."
328
329 remote_args = ['%action', '%s']
330 remote_action = ""
331 remote_action_newwin = "--new-window"
332 remote_action_newtab = ""
333 background = True
334
335 Chromium = Chrome
336
337
338 class Opera(UnixBrowser):
339 "Launcher class for Opera browser."
340
341 remote_args = ['%action', '%s']
342 remote_action = ""
343 remote_action_newwin = "--new-window"
344 remote_action_newtab = ""
345 background = True
346
347
348 class Elinks(UnixBrowser):
349 "Launcher class for Elinks browsers."
350
351 remote_args = ['-remote', 'openURL(%s%action)']
352 remote_action = ""
353 remote_action_newwin = ",new-window"
354 remote_action_newtab = ",new-tab"
355 background = False
356
357 # elinks doesn't like its stdout to be redirected -
358 # it uses redirected stdout as a signal to do -dump
359 redirect_stdout = False
360
361
362 class Konqueror(BaseBrowser):
363 """Controller for the KDE File Manager (kfm, or Konqueror).
364
365 See the output of ``kfmclient --commands``
366 for more information on the Konqueror remote-control interface.
367 """
368
369 def open(self, url, new=0, autoraise=True):
370 sys.audit("webbrowser.open", url)
•371 self._check_url(url)
372 # XXX Currently I know no way to prevent KFM from opening a new win.
373 if new == 2:
374 action = "newTab"
375 else:
376 action = "openURL"
377
378 devnull = subprocess.DEVNULL
379
380 try:
381 p = subprocess.Popen(["kfmclient", action, url],
382 close_fds=True, stdin=devnull,
383 stdout=devnull, stderr=devnull)
384 except OSError:
385 # fall through to next variant
386 pass
387 else:
388 p.wait()
389 # kfmclient's return code unfortunately has no meaning as it seems
390 return True
391
392 try:
393 p = subprocess.Popen(["konqueror", "--silent", url],
394 close_fds=True, stdin=devnull,
395 stdout=devnull, stderr=devnull,
396 start_new_session=True)
397 except OSError:
398 # fall through to next variant
399 pass
400 else:
401 if p.poll() is None:
402 # Should be running now.
403 return True
404
405 try:
406 p = subprocess.Popen(["kfm", "-d", url],
407 close_fds=True, stdin=devnull,
408 stdout=devnull, stderr=devnull,
409 start_new_session=True)
410 except OSError:
411 return False
412 else:
413 return (p.poll() is None)
414
415
416 class Grail(BaseBrowser):
417 # There should be a way to maintain a connection to Grail, but the
418 # Grail remote control protocol doesn't really allow that at this
419 # point. It probably never will!
420 def _find_grail_rc(self):
421 import glob
422 import pwd
423 import socket
424 import tempfile
425 tempdir = os.path.join(tempfile.gettempdir(),
426 ".grail-unix")
427 user = pwd.getpwuid(os.getuid())[0]
428 filename = os.path.join(glob.escape(tempdir), glob.escape(user) + "-*")
429 maybes = glob.glob(filename)
430 if not maybes:
431 return None
432 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
433 for fn in maybes:
434 # need to PING each one until we find one that's live
435 try:
436 s.connect(fn)
437 except OSError:
438 # no good; attempt to clean it out, but don't fail:
439 try:
440 os.unlink(fn)
441 except OSError:
442 pass
443 else:
444 return s
445
446 def _remote(self, action):
447 s = self._find_grail_rc()
448 if not s:
449 return 0
450 s.send(action)
451 s.close()
452 return 1
453
454 def open(self, url, new=0, autoraise=True):
455 sys.audit("webbrowser.open", url)
•456 self._check_url(url)
457 if new:
458 ok = self._remote("LOADNEW " + url)
459 else:
460 ok = self._remote("LOAD " + url)
461 return ok
462
463
464 #
465 # Platform support for Unix
466 #
467
468 # These are the right tests because all these Unix browsers require either
469 # a console terminal or an X display to run.
470
471 def register_X_browsers():
472
473 # use xdg-open if around
474 if shutil.which("xdg-open"):
475 register("xdg-open", None, BackgroundBrowser("xdg-open"))
476
477 # Opens an appropriate browser for the URL scheme according to
478 # freedesktop.org settings (GNOME, KDE, XFCE, etc.)
479 if shutil.which("gio"):
480 register("gio", None, BackgroundBrowser(["gio", "open", "--", "%s"]))
481
482 # Equivalent of gio open before 2015
483 if "GNOME_DESKTOP_SESSION_ID" in os.environ and shutil.which("gvfs-open"):
484 register("gvfs-open", None, BackgroundBrowser("gvfs-open"))
485
486 # The default KDE browser
487 if "KDE_FULL_SESSION" in os.environ and shutil.which("kfmclient"):
488 register("kfmclient", Konqueror, Konqueror("kfmclient"))
489
490 if shutil.which("x-www-browser"):
491 register("x-www-browser", None, BackgroundBrowser("x-www-browser"))
492
493 # The Mozilla browsers
494 for browser in ("firefox", "iceweasel", "iceape", "seamonkey"):
495 if shutil.which(browser):
496 register(browser, None, Mozilla(browser))
497
498 # The Netscape and old Mozilla browsers
499 for browser in ("mozilla-firefox",
500 "mozilla-firebird", "firebird",
501 "mozilla", "netscape"):
502 if shutil.which(browser):
503 register(browser, None, Netscape(browser))
504
505 # Konqueror/kfm, the KDE browser.
506 if shutil.which("kfm"):
507 register("kfm", Konqueror, Konqueror("kfm"))
508 elif shutil.which("konqueror"):
509 register("konqueror", Konqueror, Konqueror("konqueror"))
510
511 # Gnome's Galeon and Epiphany
512 for browser in ("galeon", "epiphany"):
513 if shutil.which(browser):
514 register(browser, None, Galeon(browser))
515
516 # Skipstone, another Gtk/Mozilla based browser
517 if shutil.which("skipstone"):
518 register("skipstone", None, BackgroundBrowser("skipstone"))
519
520 # Google Chrome/Chromium browsers
521 for browser in ("google-chrome", "chrome", "chromium", "chromium-browser"):
522 if shutil.which(browser):
523 register(browser, None, Chrome(browser))
524
525 # Opera, quite popular
526 if shutil.which("opera"):
527 register("opera", None, Opera("opera"))
528
529 # Next, Mosaic -- old but still in use.
530 if shutil.which("mosaic"):
531 register("mosaic", None, BackgroundBrowser("mosaic"))
532
533 # Grail, the Python browser. Does anybody still use it?
534 if shutil.which("grail"):
535 register("grail", Grail, None)
536
537 def register_standard_browsers():
538 global _tryorder
539 _tryorder = []
540
541 if sys.platform == 'darwin':
542 register("MacOSX", None, MacOSXOSAScript('default'))
543 register("chrome", None, MacOSXOSAScript('chrome'))
544 register("firefox", None, MacOSXOSAScript('firefox'))
545 register("safari", None, MacOSXOSAScript('safari'))
546 # OS X can use below Unix support (but we prefer using the OS X
547 # specific stuff)
548
549 if sys.platform == "serenityos":
550 # SerenityOS webbrowser, simply called "Browser".
551 register("Browser", None, BackgroundBrowser("Browser"))
552
553 if sys.platform[:3] == "win":
554 # First try to use the default Windows browser
555 register("windows-default", WindowsDefault)
556
557 # Detect some common Windows browsers, fallback to IE
558 iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
559 "Internet Explorer\\IEXPLORE.EXE")
560 for browser in ("firefox", "firebird", "seamonkey", "mozilla",
561 "netscape", "opera", iexplore):
562 if shutil.which(browser):
563 register(browser, None, BackgroundBrowser(browser))
564 else:
565 # Prefer X browsers if present
566 if os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"):
567 try:
568 cmd = "xdg-settings get default-web-browser".split()
569 raw_result = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
570 result = raw_result.decode().strip()
571 except (FileNotFoundError, subprocess.CalledProcessError, PermissionError, NotADirectoryError) :
572 pass
573 else:
574 global _os_preferred_browser
575 _os_preferred_browser = result
576
577 register_X_browsers()
578
579 # Also try console browsers
580 if os.environ.get("TERM"):
581 if shutil.which("www-browser"):
582 register("www-browser", None, GenericBrowser("www-browser"))
583 # The Links/elinks browsers <http://artax.karlin.mff.cuni.cz/~mikulas/links/>
584 if shutil.which("links"):
585 register("links", None, GenericBrowser("links"))
586 if shutil.which("elinks"):
587 register("elinks", None, Elinks("elinks"))
588 # The Lynx browser <http://lynx.isc.org/>, <http://lynx.browser.org/>
589 if shutil.which("lynx"):
590 register("lynx", None, GenericBrowser("lynx"))
591 # The w3m browser <http://w3m.sourceforge.net/>
592 if shutil.which("w3m"):
593 register("w3m", None, GenericBrowser("w3m"))
594
595 # OK, now that we know what the default preference orders for each
596 # platform are, allow user to override them with the BROWSER variable.
597 if "BROWSER" in os.environ:
598 userchoices = os.environ["BROWSER"].split(os.pathsep)
599 userchoices.reverse()
600
601 # Treat choices in same way as if passed into get() but do register
602 # and prepend to _tryorder
603 for cmdline in userchoices:
604 if cmdline != '':
605 cmd = _synthesize(cmdline, preferred=True)
606 if cmd[1] is None:
607 register(cmdline, None, GenericBrowser(cmdline), preferred=True)
608
609 # what to do if _tryorder is now empty?
610
611
612 #
613 # Platform support for Windows
614 #
615
616 if sys.platform[:3] == "win":
617 class WindowsDefault(BaseBrowser):
618 def open(self, url, new=0, autoraise=True):
619 sys.audit("webbrowser.open", url)
•620 self._check_url(url)
621 try:
622 os.startfile(url)
623 except OSError:
624 # [Error 22] No application is associated with the specified
625 # file for this operation: '<URL>'
626 return False
627 else:
628 return True
629
630 #
631 # Platform support for MacOS
632 #
633
634 if sys.platform == 'darwin':
635 # Adapted from patch submitted to SourceForge by Steven J. Burr
636 class MacOSX(BaseBrowser):
637 """Launcher class for Aqua browsers on Mac OS X
638
639 Optionally specify a browser name on instantiation. Note that this
640 will not work for Aqua browsers if the user has moved the application
641 package after installation.
642
643 If no browser is specified, the default browser, as specified in the
644 Internet System Preferences panel, will be used.
645 """
646 def __init__(self, name):
647 warnings.warn(f'{self.__class__.__name__} is deprecated in 3.11'
648 ' use MacOSXOSAScript instead.', DeprecationWarning, stacklevel=2)
649 self.name = name
650
651 def open(self, url, new=0, autoraise=True):
652 sys.audit("webbrowser.open", url)
•653 self._check_url(url)
654 assert "'" not in url
655 # hack for local urls
656 if not ':' in url:
657 url = 'file:'+url
658
659 # new must be 0 or 1
660 new = int(bool(new))
661 if self.name == "default":
662 # User called open, open_new or get without a browser parameter
663 script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
664 else:
665 # User called get and chose a browser
666 if self.name == "OmniWeb":
667 toWindow = ""
668 else:
669 # Include toWindow parameter of OpenURL command for browsers
670 # that support it. 0 == new window; -1 == existing
671 toWindow = "toWindow %d" % (new - 1)
672 cmd = 'OpenURL "%s"' % url.replace('"', '%22')
673 script = '''tell application "%s"
674 activate
675 %s %s
676 end tell''' % (self.name, cmd, toWindow)
677 # Open pipe to AppleScript through osascript command
678 osapipe = os.popen("osascript", "w")
679 if osapipe is None:
680 return False
681 # Write script to osascript's stdin
682 osapipe.write(script)
683 rc = osapipe.close()
684 return not rc
685
686 class MacOSXOSAScript(BaseBrowser):
687 def __init__(self, name='default'):
688 super().__init__(name)
689
690 @property
691 def _name(self):
692 warnings.warn(f'{self.__class__.__name__}._name is deprecated in 3.11'
693 f' use {self.__class__.__name__}.name instead.',
694 DeprecationWarning, stacklevel=2)
695 return self.name
696
697 @_name.setter
698 def _name(self, val):
699 warnings.warn(f'{self.__class__.__name__}._name is deprecated in 3.11'
700 f' use {self.__class__.__name__}.name instead.',
701 DeprecationWarning, stacklevel=2)
702 self.name = val
703
704 def open(self, url, new=0, autoraise=True):
705 sys.audit("webbrowser.open", url)
•706 self._check_url(url)
707 if self.name == 'default':
708 script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
709 else:
710 script = f'''
711 tell application "%s"
712 activate
713 open location "%s"
714 end
715 '''%(self.name, url.replace('"', '%22'))
716
717 osapipe = os.popen("osascript", "w")
718 if osapipe is None:
719 return False
720
721 osapipe.write(script)
722 rc = osapipe.close()
723 return not rc
724
725
726 def main():
727 import getopt
728 usage = """Usage: %s [-n | -t] url
729 -n: open new window
730 -t: open new tab""" % sys.argv[0]
731 try:
732 opts, args = getopt.getopt(sys.argv[1:], 'ntd')
733 except getopt.error as msg:
734 print(msg, file=sys.stderr)
735 print(usage, file=sys.stderr)
736 sys.exit(1)
737 new_win = 0
738 for o, a in opts:
739 if o == '-n': new_win = 1
740 elif o == '-t': new_win = 2
741 if len(args) != 1:
742 print(usage, file=sys.stderr)
743 sys.exit(1)
744
745 url = args[0]
746 open(url, new_win)
747
748 print("\a")
749
750 if __name__ == "__main__":
751 main()