Python webbrowser.Error() Examples
The following are 26
code examples of webbrowser.Error().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
webbrowser
, or try the search function
.

Example #1
Source File: _localhost_open_browser.py From webviz-config with MIT License | 7 votes |
def _get_browser_controller() -> webbrowser.BaseBrowser: if get_user_preference("browser") is not None: try: return webbrowser.get(using=get_user_preference("browser")) except webbrowser.Error: warnings.warn("Could not find the user preferred browser.") for browser in ["chrome", "chromium-browser"]: try: return webbrowser.get(using=browser) except webbrowser.Error: pass # Return default browser if none of the # preferred browsers are installed: return webbrowser.get()
Example #2
Source File: openmct.py From AIT-Core with MIT License | 6 votes |
def start_browser(self, url, name=None): browser = None if name is not None and name.lower() == 'none': log.info('Will not start any browser since --browser=none') return try: browser = webbrowser.get(name) except webbrowser.Error: old = name or 'default' msg = 'Could not find browser: %s. Will use: %s.' browser = webbrowser.get() log.warn(msg, name, self.getBrowserName(browser)) if type(browser) is webbrowser.GenericBrowser: msg = 'Will not start text-based browser: %s.' log.info(msg % self.getBrowserName(browser)) elif browser is not None: log.info('Starting browser: %s' % self.getBrowserName(browser)) browser.open_new(url)
Example #3
Source File: test_real_browser.py From aiohttp-cors with Apache License 2.0 | 6 votes |
def _run_integration_server(): """Runs integration server for interactive debugging.""" logging.basicConfig(level=logging.INFO) logger = logging.getLogger("run_integration_server") loop = asyncio.get_event_loop() servers = IntegrationServers(False, True) logger.info("Starting integration servers...") loop.run_until_complete(servers.start_servers()) try: webbrowser.open(servers.origin_server_url) except webbrowser.Error: pass try: loop.run_forever() except KeyboardInterrupt: pass finally: logger.info("Stopping integration servers...") loop.run_until_complete(servers.stop_servers())
Example #4
Source File: applications.py From zim-desktop-wiki with GNU General Public License v2.0 | 6 votes |
def __init__(self, cmd, args, retcode, stderr): '''Constructor @param cmd: the application command as string @param args: tuple of arguments given to the command @param retcode: the return code of the command (non-zero!) @param stderr: the error output of the command ''' self.msg = _('Failed to run application: %s') % cmd # T: Error message when external application failed, %s is the command self.description = \ _('%(cmd)s\nreturned non-zero exit status %(code)i') \ % {'cmd': cmd + ' "' + '" "'.join(args) + '"', 'code': retcode} # T: Error message when external application failed, %(cmd)s is the command, %(code)i the exit code if stderr: self.description += '\n\n' + stderr
Example #5
Source File: wuy.py From wuy with GNU General Public License v2.0 | 5 votes |
def __init__(self, url, size=None, chromeArgs=[]): self.__instance = None if sys.platform[:3] == "win": exe = find_chrome_win() elif sys.platform == "darwin": exe = find_chrome_mac() else: for i in ["chromium-browser", "chromium", "google-chrome", "chrome"]: try: exe = webbrowser.get(i).name break except webbrowser.Error: exe = None if exe: args = [exe, "--app=" + url] + chromeArgs if size == FULLSCREEN: args.append("--start-fullscreen") if tempfile.gettempdir(): args.append( "--user-data-dir=%s" % os.path.join(tempfile.gettempdir(), ".wuyapp") ) # self.__instance = subprocess.Popen( args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) # make troubles on windows (freezd with noconsole don't start) self.__instance = subprocess.Popen(args) else: raise Exception("no browser")
Example #6
Source File: login.py From floyd-cli with Apache License 2.0 | 5 votes |
def has_browser(): try: webbrowser.get() return True except webbrowser.Error: return False
Example #7
Source File: _user_preferences.py From webviz-config with MIT License | 5 votes |
def set_user_preferences( theme: Optional[str] = None, browser: Optional[str] = None ) -> None: preferences = ( json.loads(USER_SETTINGS_FILE.read_text()) if USER_SETTINGS_FILE.is_file() else {} ) new_preferences = {} if theme is not None: if theme not in installed_themes: raise ValueError( f"Theme {theme} is not one of the installed themes ({', '.join(installed_themes)})" ) new_preferences["theme"] = theme if browser is not None: try: webbrowser.get(using=browser) except webbrowser.Error: raise ValueError( f"Could not find an installed browser with the name {browser}." ) new_preferences["browser"] = browser if new_preferences: preferences.update(new_preferences) os.makedirs(USER_SETTINGS_FILE.parent, exist_ok=True) USER_SETTINGS_FILE.write_text(json.dumps(preferences))
Example #8
Source File: protocol.py From ensime-vim with MIT License | 5 votes |
def handle_debug_vm_error(self, call_id, payload): self.editor.raw_message('Error. Check ensime-vim log for details.')
Example #9
Source File: protocol.py From ensime-vim with MIT License | 5 votes |
def _browse_doc(self, url): self.log.debug('_browse_doc: %s', url) try: if webbrowser.open(url): self.log.info('opened %s', url) except webbrowser.Error: self.log.exception('_browse_doc: webbrowser error') self.editor.raw_message(feedback["manual_doc"].format(url))
Example #10
Source File: webbrowser.py From django-cloud-deploy with Apache License 2.0 | 5 votes |
def open_url(url: str): """Filter ugly terminal output when using webbrowser. When using webbrowser.open the follow error is shown: [20451:20471:0313/132752.481635:ERROR:browser_process_sub_thread.cc(209)] Waited 3 ms for network service. In attempts to improve UX when using the CLI, we are surpressing that error with the following utility. For more information refer to: http://man7.org/linux/man-pages/man2/dup.2.html """ # Save previous standard file descriptors prev_stderr_fd = os.dup(2) prev_stdout_fd = os.dup(1) with open(os.devnull, 'wb') as f: # redirect stderr and stdout to os.devnull os.dup2(f.fileno(), 2) os.dup2(f.fileno(), 1) try: webbrowser.open(url) except webbrowser.Error: # We are not able to do anything if any internal errors happen # with webbrowser.open() pass finally: # restore stdout and stderr os.dup2(prev_stdout_fd, 1) os.dup2(prev_stderr_fd, 2)
Example #11
Source File: webbrowser_authenticate.py From inference-model-manager with Apache License 2.0 | 5 votes |
def open_webbrowser(address): print("Your browser has been opened to visit") try: webbrowser.open(url=address, new=1) except webbrowser.Error as e: print("Unable to open the web browser: {}".format(e)) sys.exit()
Example #12
Source File: util.py From fplutil with Apache License 2.0 | 5 votes |
def open_link(url, name_of_link): """Open the given URL in the user's default webbrowser.""" try: # If possible, open in a new tab, and raise the window to the front webbrowser.open(url, new=2, autoraise=True) return True except webbrowser.Error: sys.stderr.write("\t" + name_of_link + " failed to open.\n") return False
Example #13
Source File: browser.py From loom with GNU Affero General Public License v3.0 | 5 votes |
def run(self): try: webbrowser.open(self.server_url) except webbrowser.Error: raise SystemExit('ERROR! Unable to open browser. ' 'Please manually launch a browser and ' 'navitage to this url: "%s".' % self.server_url)
Example #14
Source File: auth.py From tensorboard with Apache License 2.0 | 5 votes |
def run(self, force_console=False): """Run the flow using a local server if possible, otherwise the console.""" # TODO(b/141721828): make auto-detection smarter, especially for macOS. if not force_console and os.getenv("DISPLAY"): try: return self.run_local_server(port=0) except webbrowser.Error: sys.stderr.write( "Falling back to console authentication flow...\n" ) return self.run_console()
Example #15
Source File: pavement.py From pyrocore with GNU General Public License v2.0 | 5 votes |
def autodocs(): "create Sphinx docs locally, and start a watchdog" build_dir = path('docs/_build') index_html = build_dir / 'html/index.html' if build_dir.exists(): build_dir.rmtree() with pushd("docs"): print "\n*** Generating API doc ***\n" sh("sphinx-apidoc -o apidoc -f -T ../src/pyrocore") sh("sphinx-apidoc -o apidoc -f -T $(dirname $(python -c 'import tempita; print(tempita.__file__)'))") print "\n*** Generating HTML doc ***\n" sh('command . ../bin/activate && ' 'nohup %s/Makefile SPHINXBUILD="sphinx-autobuild -p %d' ' -i \'.*\' -i \'*.log\' -i \'*.png\' -i \'*.txt\'" html >autobuild.log 2>&1 &' % (os.getcwd(), SPHINX_AUTOBUILD_PORT)) for i in range(25): time.sleep(2.5) pid = watchdog_pid() if pid: sh("touch docs/index.rst") sh('ps {}'.format(pid)) url = 'http://localhost:{port:d}/'.format(port=SPHINX_AUTOBUILD_PORT) try: import webbrowser webbrowser.open_new_tab(url) except webbrowser.Error: print("\n*** Open '{}' in your browser...".format(url)) break
Example #16
Source File: conftest.py From coala with GNU Affero General Public License v3.0 | 5 votes |
def pytest_unconfigure(config): htmlcov_path = os.path.join('htmlcov', 'index.html') if (hasattr(config.option, 'cov_report') and 'html' in config.option.cov_report and os.path.isfile(htmlcov_path)): try: webbrowser.open_new_tab(htmlcov_path) except webbrowser.Error: pass
Example #17
Source File: oauth2.py From spotipy with MIT License | 5 votes |
def _open_auth_url(self): auth_url = self.get_authorize_url() try: webbrowser.open(auth_url) logger.info("Opened %s in your browser", auth_url) except webbrowser.Error: logger.error("Please navigate here: %s", auth_url)
Example #18
Source File: oauth2.py From spotipy with MIT License | 5 votes |
def _open_auth_url(self, state=None): auth_url = self.get_authorize_url(state) try: webbrowser.open(auth_url) logger.info("Opened %s in your browser", auth_url) except webbrowser.Error: logger.error("Please navigate here: %s", auth_url)
Example #19
Source File: applications.py From zim-desktop-wiki with GNU General Public License v2.0 | 5 votes |
def __init__(self): import webbrowser self.controller = None try: self.controller = webbrowser.get() except webbrowser.Error: pass # webbrowser throws an error when no browser is found
Example #20
Source File: urls.py From rednotebook with GNU General Public License v2.0 | 5 votes |
def open_url_in_browser(url): try: logging.info("Trying to open %s with webbrowser" % url) webbrowser.open(url) except webbrowser.Error: logging.exception("Failed to open web browser")
Example #21
Source File: slideshow.py From me-ica with GNU Lesser General Public License v2.1 | 4 votes |
def show_image_slideshow(filenames, image_size, filename=None, title=None, section_ids=None, delay=100, delay_delta=20, loop=True, slideshow_id=None, magnification=1, mag_control=True, open_browser=True): """Write the slideshow into a HTML file, open it in the browser and return a file object pointing to the file. If the filename is not given, a temporary file is used, and will be deleted when the returned file object is closed or destroyed. filenames -- Sequence of the image filenames. image_size -- Tuple (x,y) with the original image size, or enter a different size to force scaling. filename -- Filename for the HTML file to be created. If None a temporary file is created. title -- Optional slideshow title (for default None not title is shown). section_ids -- List with the section id for each slide index. The id can be a string or a number. Default value None disables the section feature. open_browser -- If True (default value) then the slideshow file is automatically opened in a webbrowser. One can also use string value with the browser name (for webbrowser.get) to request a specific browser. For additional keyword arguments see the ImageHTMLSlideShow class. """ if filename is None: html_file = tempfile.NamedTemporaryFile(suffix=".html", prefix="MDP_") else: html_file = open(filename, 'w') html_file.write('<html>\n<head>\n<title>%s</title>\n' % title) html_file.write('<style type="text/css" media="screen">') html_file.write(basic_css() + image_slideshow_css()) html_file.write('</style>\n</head>\n<body>\n') kwargs = vars() del kwargs['filename'] del kwargs['open_browser'] del kwargs['html_file'] html_file.write(image_slideshow(**kwargs)) html_file.write('</body>\n</html>') html_file.flush() if open_browser: if isinstance(open_browser, str): try: custom_browser = webbrowser.get(open_browser) custom_browser.open(os.path.abspath(filename)) except webbrowser.Error: err = ("Could not open browser '%s', using default." % open_browser) warnings.warn(err) webbrowser.open(os.path.abspath(filename)) else: webbrowser.open(os.path.abspath(filename)) return html_file
Example #22
Source File: notebookapp.py From Computable with MIT License | 4 votes |
def start(self): """ Start the IPython Notebook server app, after initialization This method takes no arguments so all configuration and initialization must be done prior to calling this method.""" ip = self.ip if self.ip else '[all ip addresses on your system]' proto = 'https' if self.certfile else 'http' info = self.log.info self._url = "%s://%s:%i%s" % (proto, ip, self.port, self.base_project_url) for line in self.notebook_info().split("\n"): info(line) info("Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).") if self.open_browser or self.file_to_run: ip = self.ip or LOCALHOST try: browser = webbrowser.get(self.browser or None) except webbrowser.Error as e: self.log.warn('No web browser found: %s.' % e) browser = None if self.file_to_run: name, _ = os.path.splitext(os.path.basename(self.file_to_run)) url = self.notebook_manager.rev_mapping.get(name, '') else: url = '' if browser: b = lambda : browser.open("%s://%s:%i%s%s" % (proto, ip, self.port, self.base_project_url, url), new=2) threading.Thread(target=b).start() try: ioloop.IOLoop.instance().start() except KeyboardInterrupt: info("Interrupted...") finally: self.cleanup_kernels() #----------------------------------------------------------------------------- # Main entry point #-----------------------------------------------------------------------------
Example #23
Source File: awsrecipes_enable_mfa.py From AWS-recipes with GNU General Public License v2.0 | 4 votes |
def display_qr_code(png, seed): """ Display MFA QR code :param png: :param seed: :return: """ # This NamedTemporaryFile is deleted as soon as it is closed, so # return it to caller, who must close it (or program termination # could cause it to be cleaned up, that's fine too). # If we don't keep the file around until after the user has synced # his MFA, the file will possibly be already deleted by the time # the operating system gets around to execing the browser, if # we're using a browser. qrcode_file = tempfile.NamedTemporaryFile(suffix='.png', delete=True, mode='wt') qrcode_file.write(png) qrcode_file.flush() if _fabulous_available: fabulous.utils.term.bgcolor = 'white' with open(qrcode_file.name, 'rb') as png_file: print(fabulous.image.Image(png_file, 100)) else: graphical_browsers = [webbrowser.BackgroundBrowser, webbrowser.Mozilla, webbrowser.Galeon, webbrowser.Chrome, webbrowser.Opera, webbrowser.Konqueror] if sys.platform[:3] == 'win': graphical_browsers.append(webbrowser.WindowsDefault) elif sys.platform == 'darwin': graphical_browsers.append(webbrowser.MacOSXOSAScript) browser_type = None try: browser_type = type(webbrowser.get()) except webbrowser.Error: pass if browser_type in graphical_browsers: printError("Unable to print qr code directly to your terminal, trying a web browser.") webbrowser.open('file://' + qrcode_file.name) else: printInfo("Unable to print qr code directly to your terminal, and no graphical web browser seems available.") printInfo("But, the qr code file is temporarily available as this file:") printInfo("\n %s\n" % qrcode_file.name) printInfo("Alternately, if you feel like typing the seed manually into your MFA app:") # this is a base32-encoded binary string (for case # insensitivity) which is then dutifully base64-encoded by # amazon before putting it on the wire. so the actual # secret is b32decode(b64decode(seed)), and what users # will need to type in to their app is just # b64decode(seed). print that out so users can (if # desperate) type in their MFA app. printInfo("\n %s\n" % base64.b64decode(seed)) return qrcode_file
Example #24
Source File: awsrecipes_enable_mfa.py From AWS-recipes with GNU General Public License v2.0 | 4 votes |
def main(): # Parse arguments parser = OpinelArgumentParser() parser.add_argument('debug') parser.add_argument('profile') parser.add_argument('user-name', help = 'Your username (automatically fetched using iam:GetUser if not provided).') args = parser.parse_args() # Configure the debug level configPrintException(args.debug) # Check version of opinel if not check_requirements(os.path.realpath(__file__)): return 42 # Arguments profile_name = args.profile[0] user_name = args.user_name[0] # Search for AWS credentials credentials = read_creds(profile_name) if not credentials['AccessKeyId']: return 42 # Connect to IAM iam_client = connect_service('iam', credentials) if not iam_client: printError('Error: failed to create IAM API client.') return 42 # Set the user name if not user_name: try: printInfo('Searching for username...') user_name = iam_client.get_user()['User']['UserName'] if not user_name: printInfo('Error: could not find user name to enable MFA for.') return 42 except Exception as e: configPrintException(e) # Create and activate the MFA device credentials['SerialNumber'] = enable_mfa(iam_client, user_name) # Update the credentials file write_creds_to_aws_credentials_file(profile_name, credentials) sample_command = 'awsrecipes_init_sts_session.py %s' % (('--profile %s' % profile_name) if profile_name != 'default' else '') printInfo('Your credentials file has been updated.\n' \ 'You may now initiate STS sessions to access the AWS APIs with the following command:\n' \ '\n %s\n' % sample_command)
Example #25
Source File: serve.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
def postprocess(self, input): """Serve the build directory with a webserver.""" dirname, filename = os.path.split(input) handlers = [ (r"/(.+)", web.StaticFileHandler, {'path' : dirname}), (r"/", web.RedirectHandler, {"url": "/%s" % filename}) ] if ('://' in self.reveal_prefix or self.reveal_prefix.startswith("//")): # reveal specifically from CDN, nothing to do pass elif os.path.isdir(os.path.join(dirname, self.reveal_prefix)): # reveal prefix exists self.log.info("Serving local %s", self.reveal_prefix) else: self.log.info("Redirecting %s requests to %s", self.reveal_prefix, self.reveal_cdn) handlers.insert(0, (r"/(%s)/(.*)" % self.reveal_prefix, ProxyHandler)) app = web.Application(handlers, cdn=self.reveal_cdn, client=AsyncHTTPClient(), ) # hook up tornado logging to our logger log.app_log = self.log http_server = httpserver.HTTPServer(app) http_server.listen(self.port, address=self.ip) url = "http://%s:%i/%s" % (self.ip, self.port, filename) print("Serving your slides at %s" % url) print("Use Control-C to stop this server") if self.open_in_browser: try: browser = webbrowser.get(self.browser or None) b = lambda: browser.open(url, new=2) threading.Thread(target=b).start() except webbrowser.Error as e: self.log.warning('No web browser found: %s.' % e) browser = None try: ioloop.IOLoop.instance().start() except KeyboardInterrupt: print("\nInterrupted")
Example #26
Source File: twitchy_play.py From twitchy with GNU General Public License v3.0 | 4 votes |
def play(self): # Display chat in a fresh browser window as a popup if Options.chat.enable: chat_url = f'http://www.twitch.tv/{self.channel_name}/chat?popout=' try: webbrowser.get('chromium').open_new(f'--app={chat_url}') except webbrowser.Error: webbrowser.open_new(chat_url) except TypeError: webbrowser.get('chromium').open_new(f'--app={chat_url}') # WTF? # Insert the name of only started games into the database # This keeps the database from getting too cluttered display_name = self.channel_params['display_name'] player = Options.video.player_final if player[:3] == 'mpv': player += f' --title={display_name}' quality = Options.quality_map[self.channel_params['quality']] # The following prints to the console # If ever there is going to be a curses version # it will need to be suppressed if twitchy_config.print_to_stdout: print(' ' + Colors.WHITE + self.channel_params['display_name'] + Colors.ENDC + ' | ' + Colors.WHITE + self.channel_params['quality'].title() + Colors.ENDC) args_to_subprocess = ( f"streamlink twitch.tv/{self.channel_name} {quality} --player '{player}'") hls_settings = ' --hls-segment-threads 3' args_to_subprocess = shlex.split(args_to_subprocess + hls_settings) # Get the time when the stream starts self.start_time = time.time() if twitchy_config.non_interactive_mode: self.player_process = subprocess.Popen( args_to_subprocess, preexec_fn=os.setpgrp, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) exit(0) else: self.player_process = subprocess.Popen( args_to_subprocess, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setpgrp)