Debian Codegraph @

lib-python/3/webbrowser.py

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