我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用webbrowser.open_new_tab()。
def run_tests_if_main(show_coverage=False): """ Run tests in a given file if it is run as a script Coverage is reported for running this single test. Set show_coverage to launch the report in the web browser. """ local_vars = inspect.currentframe().f_back.f_locals if not local_vars.get('__name__', '') == '__main__': return # we are in a "__main__" os.chdir(ROOT_DIR) fname = str(local_vars['__file__']) _clear_imageio() _enable_faulthandler() pytest.main('-v -x --color=yes --cov imageio ' '--cov-config .coveragerc --cov-report html %s' % repr(fname)) if show_coverage: import webbrowser fname = os.path.join(ROOT_DIR, 'htmlcov', 'index.html') webbrowser.open_new_tab(fname)
def open_in_browser(url, browser_name = '', browser_path = ''): if not browser_path or not os.path.exists(browser_path) or browser_name == "default": webbrowser.open_new_tab(url) elif browser_name == "chrome-private": # os.system("\"%s\" --incognito %s" % (browser_path, url)) browser = webbrowser.get('"' + browser_path +'" --incognito %s') browser.open(url) else: try: # show_in_panel("33") # browser_path = "\"C:\Program Files\Google\Chrome\Application\chrome.exe\" --incognito" webbrowser.register('chromex', None, webbrowser.BackgroundBrowser(browser_path)) webbrowser.get('chromex').open_new_tab(url) except Exception as e: webbrowser.open_new_tab(url)
def read(item_id, open_origin, archive): article = pocket_app.find_article(item_id) if not article: print('Article with this ID was not found.') url = 'https://getpocket.com/a/read/{}'.format(article['id']) print(format_article(article, header='Selected Article')) if open_origin: url = article['url'] webbrowser.open_new_tab(url) if archive: pocket_app.archive_article(article['id'])
def invoke(self, context, event): import webbrowser st = context.space_data # get the selected text text = self.get_selected_text(st.text) # if no text is selected send the whole file if text is None: text = st.text.as_string() # send the text and receive the returned page page = self.send_text(text) if page is None: return {'CANCELLED'} # store the link in the clipboard bpy.context.window_manager.clipboard = page if context.scene.use_webbrowser: try: webbrowser.open_new_tab(page) except: self.report({'WARNING'}, "Error in opening the page %s." % (page)) return {'FINISHED'}
def auth_via_browser(self, perms=u'read'): """Opens the webbrowser to authenticate the given request request_token, sets the verifier. Use this method in stand-alone apps. In webapps, use auth_url(...) instead, and redirect the user to the returned URL. Updates the given request_token by setting the OAuth verifier. """ import webbrowser # The HTTP server may have been started already, but we're not sure. Just start # it if it needs to be started. self._start_http_server() url = self.auth_url(perms) if not webbrowser.open_new_tab(url): raise exceptions.FlickrError('Unable to open a browser to visit %s' % url) self.verifier = self.auth_http_server.wait_for_oauth_verifier() # We're now done with the HTTP server, so close it down again. self._stop_http_server()
def setUp(self): self.api_client = docusign.ApiClient(BASE_URL) # IMPORTANT NOTE: # the first time you ask for a JWT access token, you should grant access by making the following call # get DocuSign OAuth authorization url: oauth_login_url = self.api_client.get_jwt_uri(integrator_key, redirect_uri, oauth_base_url) # open DocuSign OAuth authorization url in the browser, login and grant access # webbrowser.open_new_tab(oauth_login_url) print(oauth_login_url) # END OF NOTE # configure the ApiClient to asynchronously get an access to token and store it self.api_client.configure_jwt_authorization_flow(private_key_filename, oauth_base_url, integrator_key, user_id, 3600) docusign.configuration.api_client = self.api_client
def before_exit(): lines_of_code = process_history() if not PySession.save or len(lines_of_code) == 0: stdout.write(DO_NOTHING) return filename = expanduser(os.getenv('PYSESSION_FILENAME', 'session.py')) if PySession.save_locally: stdout.write(SAVING_FILE.format(filename=filename)) PySession.save_to_file('\n'.join(lines_of_code), filename) stdout.write(SUCCESS) return try: stdout.write(SAVING_GIST.format(filename=filename)) gist_response = PySession.save_to_gist('\n'.join(lines_of_code), filename) gist_url = gist_response['html_url'] PySession.save_gist_url(gist_url) webbrowser.open_new_tab(gist_url) stdout.write(SUCCESS) except: stdout.write(FAILED) PySession.save_to_file('\n'.join(lines_of_code), filename)
def run(self, edit): self.window = self.view.window() v = self.view if len(v.sel()) != 1: return cursor = v.sel()[0].a line_range = v.line(cursor) line_content = v.substr(line_range).strip() matched = self.is_valid_line(line_content) if matched: destination_str = matched.group(1) file_path = HyperClickPathResolver(v, destination_str, self.roots, self.lang, self.settings ) resolved_path = file_path.resolve() if resolved_path: if resolved_path.startswith('http://') or resolved_path.startswith('https://'): webbrowser.open_new_tab(resolved_path) else: self.window.open_file(resolved_path)
def run_register(args): api_client = ApiClient() client = AdminApi(api_client) account = call_api(lambda: client.get_account_info()) if account.key is not None: print('Note: this cluster is already registered with an account. ' 'You can continue and register with another account.') read_and_register_account_key() else: key_exists = read_yes_no('Do you already have an account key') if key_exists: read_and_register_account_key() else: register_url = get_riseml_url() + 'register/basic/%s' % account.cluster_id if browser_available(): webbrowser.open_new_tab(register_url) else: print('Please visit this URL and follow instructions' ' to register an account: %s' % register_url) read_and_register_account_key()
def _start_server(port, web_dir): """ Parameters ---------- port : localhost port to start server on web_dir: directory containing server files Returns ------- None """ _os.chdir(web_dir) import subprocess import webbrowser if port is None: port = _np.random.randint(8000, 9000) subprocess.Popen(['python', '-m', 'SimpleHTTPServer', str(port)]) webbrowser.open_new_tab('localhost:{}'.format(str(port)))
def on_menuitem_preview_browser_activate(self, widget): # Create a temporary HTML file tf = tempfile.NamedTemporaryFile(delete = False) self.temp_file_list.append(tf) tf_name = tf.name text = self.text_buffer.get_text(self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), False) dirname = os.path.dirname(self.name) text = re.sub(r'(\!\[.*?\]\()([^/][^:]*?\))', lambda m, dirname=dirname: m.group(1) + os.path.join(dirname, m.group(2)), text) try: html_middle = markdown.markdown(text, self.default_extensions) except: try: html_middle = markdown.markdown(text, extensions =self.safe_extensions) except: html_middle = markdown.markdown(text) html = self.default_html_start + html_middle + self.default_html_end tf.write(html.encode()) tf.flush() # Load the temporary HTML file in the user's default browser webbrowser.open_new_tab(tf_name)
def update_check(parent): """Check for updates using the GitHub API Args: parent (wx.Window): The parent window (for the message dialog) Returns: None """ r = requests.get('https://api.github.com/repos/10se1ucgo/pyjam/releases/latest') if not r.ok: return new = r.json()['tag_name'] try: if StrictVersion(__version__) < StrictVersion(new.lstrip('v')): info = wx.MessageDialog(parent, message="pyjam {v} is now available!\nGo to download page?".format(v=new), caption="pyjam Update", style=wx.OK | wx.CANCEL | wx.ICON_INFORMATION) if info.ShowModal() == wx.ID_OK: webbrowser.open_new_tab(r.json()['html_url']) info.Destroy() except ValueError: pass
def login(): # Import in here for performance reasons import webbrowser # TODO: use Oauth and a local webserver: https://community.auth0.com/questions/6501/authenticating-an-installed-cli-with-oidc-and-a-th url = api.app_url + '/profile' # TODO: google cloud SDK check_browser.py launched = webbrowser.open_new_tab(url) if launched: click.echo( 'Opening [{0}] in a new tab in your default browser.'.format(url)) else: click.echo("You can find your API keys here: {0}".format(url)) key = click.prompt("{warning} Paste an API key from your profile".format( warning=click.style("Not authenticated!", fg="red")), value_proc=lambda x: x.strip()) if key: # TODO: get the username here... # username = api.viewer().get('entity', 'models') write_netrc(api.api_url, "user", key)
def show(self, fmt="html", header_block=None, footer_block=None): """ Show the block in a browser. :param fmt: The format of the saved block. Supports the same output as `Block.save` :return: Path to the block file. """ file_name = str_base(hash(self._id)) + "." + fmt file_path = self.publish(os.path.expanduser(os.path.join(user_config["tmp_html_dir"], file_name)), header_block=header_block, footer_block=footer_block) try: url_base = user_config["public_dir"] except KeyError: path = os.path.expanduser(file_path) else: path = urljoin(url_base, os.path.expanduser(user_config["tmp_html_dir"] + "/" + file_name)) webbrowser.open_new_tab(path) return path
def opencov(self, syncDir, job_type, job_id): cov_web_indexhtml = syncDir + "/cov/web/index.html" if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, cov_web_indexhtml), 'Opening coverage html for {} job ID [{}]'.format(job_type, job_id), indent=2, fail_msg=self.fail_msg): return False if self.test: return True webbrowser.open_new_tab(cov_web_indexhtml) return True # TODO: Add feature # def opencov_abtests(self): # # control_sync = '{}/{}/afl-out'.format(self.job_token.rootdir, self.job_token.joba_id) # exp_sync = '{}/{}/afl-out'.format(self.job_token.rootdir, self.job_token.jobb_id) # # if not self.opencov(control_sync, self.job_token.type, self.job_token.joba_id): # return False # if not self.opencov(exp_sync, self.job_token.type, self.job_token.jobb_id): # return False # return True
def click(self): if self.name == "Blog": webbrowser.open_new_tab(URL + "/blog") if self.name == "My Courses": webbrowser.open_new_tab(URL + "/courses/enrolled") if self.name == "All Courses": webbrowser.open_new_tab(URL + "/courses") if self.name == "Personal Coach": webbrowser.open_new_tab(URL + "/p") if self.name == "Donate": webbrowser.open_new_tab("https://www.patreon.com/cleverprogrammer?sa=eyJ1c2VyX2lkIjoyNzE4MzQwLCJleHBpcmVzX2F0IjoxNDg2MDg0NzUxLCJzY2hvb2xfaWQiOjQ1MjQ4LCJhdXRoZW50aWNhdGlvbl90b2tlbiI6InN4bXdleTQ1ZUNGTHN5eC0yRjJ4ZFNYSGtOanhhd0tmMmcifQ%3D%3D--90aaa087ebabde35b8c39bf25f1ebf9fd4366b5f") if self.name == "Learn Python OOP": webbrowser.open_new_tab(URL + "/courses/enrolled/130834") if self.name == "Learn Python": webbrowser.open_new_tab(URL + "/courses/enrolled/105512)") if self.name == "Codecademy Python Walkthrough and Tutorial Series": webbrowser.open_new_tab(URL + "/p/python-walkthrough-and-tutorial-series-2016") else: webbrowser.open_new_tab(URL)
def run(self, edit, *args, **kwargs): self.window = self.view.window() self.selection = sublime.Selection(self.view.id()) self.settings = self.view.settings() for region in self.view.sel(): # pygame.draw.circle text = self.view.substr(region) text = 'pygame.draw.circle' if text.startswith('pygame.'): text = text[len('pygame.'):] module, method = text.split('.') path = PATH_TO_PYGAME_DOC + '/' + module + '.html#' + module + '.' + method webbrowser.open_new_tab(path)
def on_navigate(self, href): """ open the link in a new tab on web browser """ if '$$$' in href: try: arr = href.split('$$$') file_name = arr[0].strip() location = arr[1].split(',') row = int(location[0].strip()) col = int(location[1].strip()) sublime.active_window().open_file("%s:%s:%s" % (file_name, row, col), sublime.ENCODED_POSITION) except Exception as e: # print(e) self.logger_msg += str(e) + '\n' else: try: webbrowser.open_new_tab(href) except Exception as e: # logging.error('cannot open link on web browser.') self.logger_msg += str(e) + '\n'
def open_id_web(self): """ Open currently displayed computer record in jamf """ self.logger.info("%s: activated" % inspect.stack()[0][3]) if self.id_string.get(): url_formatted = self.jamf_hostname + "/computers.html?id=" + self.id_string.get() + "&o=r" webbrowser.open_new_tab(url_formatted) self.logger.info("%s: Opened id web. (%s)" % (inspect.stack()[0][3], self.id_string.get())) self.status_label.configure(style='Normal.TLabel') self.status_string.set("Opened URL for ID.") else: self.logger.error("%s: No computer id available." % inspect.stack()[0][3]) self.status_label.configure(style='Warning.TLabel') self.status_string.set("No ID available.")
def open_search_web(self): """ Open currently displayed search in jamf """ self.logger.info("%s: activated" % inspect.stack()[0][3]) if self.search_string.get(): url_formatted = self.jamf_hostname + "/computers.html?queryType=Computers&query=*" + self.search_string.get() + "*" webbrowser.open_new_tab(url_formatted) self.logger.info("%s: Opened search web. (%s)" % (inspect.stack()[0][3], self.search_string.get())) self.status_label.configure(style='Normal.TLabel') self.status_string.set("Opened URL for search.") else: self.logger.error("%s: No search string available." % inspect.stack()[0][3]) self.status_label.configure(style='Warning.TLabel') self.status_string.set("No search string entered.")
def run(self, mode=None, count=None): if len(self.view.sel()) != 1: return sel = self.view.sel()[0] line = self.view.line(sel) text = self.view.substr(line) url = self.__class__._url(self.URL_REGEX, text) if url: webbrowser.open_new_tab(url) # https://vimhelp.appspot.com/scroll.txt.html#CTRL-E
def configure(consumer_key, sort_field, words_per_minute): pocket_app.init_consumer_key(consumer_key) request_token = pocket_app.get_request_token() if not request_token: print('Could not obtain request_token') return url = 'http://getpocket.com/auth/authorize?request_token={0}' \ '&redirect_uri={1}'.format(request_token, 'http://www.google.com') print('You will have to authorize the application to access your articles') print('Enter any key once you\'re redirected to google.com') print('Or open this link in browser manually:') print(url); webbrowser.open_new_tab(url) input() access_token = pocket_app.get_access_token(request_token) if not access_token: print('Could not obtain access token') return pocket_app.configure(consumer_key, access_token, words_per_minute, sort_field) print('The application is ready to use')
def random_article(browser, archive): articles = pocket_app.get_articles() article = random.choice(articles) print(format_article(article, header='Selected Article', line=True)) if browser: webbrowser.open_new_tab(article['url']) if archive: pocket_app.archive_article(article['id'])
def submit_err(error_msg,no_solution): print "\n" print "Please wait ................ " print "Pyoverflow is checking for the top solutions for your code problems" print ":)" print "\n" try: search_word = "python"+" "+str(error_msg) for url in search(search_word, stop=2): search_result.append(url) except Exception as e: print e sys.exit(0) try: if(int(no_solution) > 0): for i in range(0,int(no_solution)): #print search_result[i] print "Opening"+"\t"+str(i)+" solution in browser" webbrowser.open_new_tab(search_result[i]) else: print "Number of solutions should be > 0" except Exception as e: print e sys.exit(0)
def readme(ctx, browse=False): """Build README.rst. Requires Sphinx.""" ctx.run("rst2html.py README.rst > README.html") if browse: webbrowser.open_new_tab('README.html')
def helpPagesOpen(self): webbrowser.open_new_tab(self.homepage_url) webbrowser.open_new_tab(self.forum_url) webbrowser.open_new_tab(self.wiki_url) """QDesktopServices.openUrl(QUrl(self.homepage_url)) QDesktopServices.openUrl(QUrl(self.forum_url)) QDesktopServices.openUrl(QUrl(self.wiki_url))"""
def _show_changelog(): webbrowser.open_new_tab(constant.LINK_CHANGELOG)
def show_file_or_folder_in_explorer(path: Path or str): if isinstance(path, str) and path.startswith('http'): webbrowser.open_new_tab(path) return if isinstance(path, str): path = Path(path) if not path.exists(): raise FileNotFoundError(str(path.abspath())) if path.isdir(): os.startfile(str(path.abspath())) elif path.isfile(): os.startfile(str(path.dirname().abspath()))
def open_pr(self, url): """ open url in the web browser """ if self.dry_run: click.echo(f" dry-run: Create new PR: {url}") else: click.echo("Backport PR URL:") click.echo(url) webbrowser.open_new_tab(url)
def openGameReport(self): selected = self.get_selectedMatches() if selected: for match in selected: webbrowser.open_new_tab('https://www.fupa.net/spielberichte/xxx-xxx-xxx-%d.html' % match['match_id'])
def oauth_dance(redis_client, conf, bottle_app, file_event_handler, bottle_thread=None): diycrate_secret_key = redis_client.get('diycrate_secret_key') or str(uuid.uuid4()) if not redis_client.exists('diycrate_secret_key'): redis_client.set('diycrate_secret_key', diycrate_secret_key) bottle_app.oauth = file_event_handler.oauth = setup_remote_oauth(redis_client) import requests auth_url, bottle_app.csrf_token = requests.get(conf['box']['authorization_url'], data={'redirect_url': 'https://localhost:8080/', }, verify=False).json() # auth_url, bottle_app.csrf_token = bottle_app.oauth.get_authorization_url(auth_url) if bottle_thread and not bottle_thread.is_alive(): bottle_thread.start() webbrowser.open_new_tab(auth_url) # make it easy for the end-user to start auth
def main(): build_project_path = '_build' if not os.path.exists(build_project_path): os.system('make html') server = Server() server.watch('./*.rst', shell('make html')) server.watch('./*/*.rst', shell('make html')) webbrowser.open_new_tab('http://127.0.0.1:5500') server.serve(root='_build/html')
def watch(game, show, template, in_window, use_streamlink, quality, just_print): matches = list(download_matches(game)) if not show: matches = [m for m in matches if m.get('stream')] if not matches: click.echo('No streams found :(') return template = template if template else DEFAULT_TEMPLATE_ALL if game == 'all' else DEFAULT_TEMPLATE template = Template(template) items = ['{}: {}'.format(i, template.render(m)) for i, m in enumerate(matches)] for item in items: click.echo(item) click.echo('-' * len(sorted(items)[0])) while True: click.echo('select stream to show: ', nl=False) choice = input('') if not choice.isdigit(): click.echo(' "{}" is not a number'.format(choice)) continue choice = int(choice) if choice not in range(0, len(matches)): click.echo(' {} is out of range'.format(choice)) continue break selected = matches[choice].get('stream') if not selected: click.secho('cannot stream for match #{}: no stream'.format(choice), err=True, fg='red') return if just_print: click.echo(selected) return click.echo('Opening {}...'.format(selected)) if use_streamlink: subprocess.Popen(['nohup streamlink "{}" {} &'.format(selected, quality)], shell=True, start_new_session=True) elif not in_window: webbrowser.open_new_tab(selected) else: webbrowser.open(selected, new=1)
def openURL(self, url): self.log.debug("Open URL %s" % url) webbrowser.open_new_tab(url) self.loop.screen.clear()
def run(self, online=False): if online: webbrowser.open_new_tab('http://requester.org') return show_read_only_doc_view(self.window.new_file(), sublime.load_resource('Packages/Requester/docs/_content/body.md'), 'Requester Documentation')
def run(self): webbrowser.open_new_tab('http://docs.python-requests.org/en/master/user/quickstart/')
def open_in_browser(self): webbrowser.open_new_tab(str(self))
def run(self): webbrowser.open_new_tab("https://github.com/notifications")
def get_update(self): url = DOWNLOAD_PAGE if self.update: latest = '/tag/v{}'.format(self.newversion) url = url + latest webbrowser.open_new_tab(url)
def execute(self, context): webbrowser.open_new_tab(url) return {'FINISHED'}
def open_in_default_browser(url): browser_map = setting.get_default_browser() browser_name = browser_map['name'] browser_path = browser_map['path'] if not browser_path or not os.path.exists(browser_path) or browser_name == "default": webbrowser.open_new_tab(url) elif browser_map['name'] == "chrome-private": # chromex = "\"%s\" --incognito %s" % (browser_path, url) # os.system(chromex) browser = webbrowser.get('"' + browser_path +'" --incognito %s') browser.open(url) # os.system("\"%s\" -ArgumentList @('-incognito', %s)" % (browser_path, url)) else: try: webbrowser.register('chromex', None, webbrowser.BackgroundBrowser(browser_path)) webbrowser.get('chromex').open_new_tab(url) except Exception as e: webbrowser.open_new_tab(url) ########################################################################################## #END ##########################################################################################
def on_navigate(self, href): """ open the link in a new tab on web browser """ try: webbrowser.open_new_tab(href) except Exception as e: logging.error('cannot open link on web browser.')
def on_navigate(self, url): if url.startswith('http://') or url.startswith('https://'): webbrowser.open_new_tab(url) else: self.window.open_file(url)
def _default_show_url(url): import webbrowser webbrowser.open_new_tab(url)
def show_wiki(self, widget): webbrowser.open_new_tab('http://inguma.eu/projects/bokken/wiki')
def on_link_clicked(self, link, _=None): """Event for clicked link.""" webbrowser.open_new_tab(self.preferences["urls"][link.get_name()])
def run_upgrade(args): api_client = ApiClient() client = AdminApi(api_client) account = call_api(lambda: client.get_account_info()) if account.key is None: print('You have not registered with an account. ' 'Please run ' + bold('riseml account register')) else: register_url = get_riseml_url() + 'upgrade/%s' % account.key if browser_available(): webbrowser.open_new_tab(register_url) else: print('Please visit this URL and follow instructions' ' to upgrade your account: %s' % register_url)
def openurl(url): webbrowser.open_new_tab(url)