Python webbrowser.open_new_tab() Examples

The following are 30 code examples of webbrowser.open_new_tab(). 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: page.py    From awe with MIT License 7 votes vote down vote up
def start(self, block=False, open_browser=True, develop=False):
        """
        Start the page services.

        :param block: Should the method invocation block. (default: ``False``)
        :param open_browser: Should a new tab be opened in a browser pointing to the started page. (default: ``True``)
        :param develop: During development, changes to port for open browser to ``3000``.
               (due to npm start, default ``False``)
        """
        if self._started:
            return
        if self._offline:
            self._element_updater.start()
            return
        self._message_handler.start()
        self._server.start()
        self._ws_server.start()
        self._element_updater.start()
        self._started = True
        if open_browser:
            port = 3000 if (develop or os.environ.get('AWE_DEVELOP')) else self._port
            webbrowser.open_new_tab('http://localhost:{}'.format(port))
        if block:
            self.block() 
Example #2
Source File: util.py    From SalesforceXyTools with Apache License 2.0 7 votes vote down vote up
def open_in_default_browser(sf_basic_config, url):
    browser_map = sf_basic_config.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
########################################################################################## 
Example #3
Source File: util.py    From SalesforceXyTools with Apache License 2.0 7 votes vote down vote up
def open_in_browser(sf_basic_config, url, browser_name = '', browser_path = ''):
    settings =  sf_basic_config.get_setting()
    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) 
Example #4
Source File: custom.py    From azure-cli-extensions with MIT License 6 votes vote down vote up
def open_codespace(cmd, client, plan_name, resource_group_name=None, codespace_id=None,
                   codespace_name=None, do_not_prompt=None):
    token = client.write_environments_action(resource_group_name=resource_group_name, plan_name=plan_name)
    if codespace_name:
        codespace_id = _determine_codespace_id(
            client, resource_group_name, plan_name, token, codespace_name, cli_ctx=cmd.cli_ctx)
    codespace = cs_api.get_codespace(token.access_token, codespace_id, cli_ctx=cmd.cli_ctx)
    if not do_not_prompt and codespace['state'] != 'Available':
        msg = f"Current state of the codespace is '{codespace['state']}'." \
            " Continuing will cause the environment to be resumed.\nDo you want to continue?"
        user_confirmed = prompt_y_n(msg)
        if not user_confirmed:
            raise CLIError("Operation cancelled.")
    domain = cs_config.get_service_domain(cmd.cli_ctx)
    url = f"https://{domain}/environment/{codespace['id']}"
    logger.warning("Opening: %s", url)
    success = webbrowser.open_new_tab(url)
    if not success:
        raise CLIError("Unable to open browser") 
Example #5
Source File: servers.py    From quantipy with MIT License 6 votes vote down vote up
def webeditor(obj, host="localhost", port=8000):
    cleanup_tmp_folder()
    url = "http://{host}:{port}/core/srv/tmp/webedit.html".format(
    	host=host, 
    	port=port)

    json_string = json.dumps(obj, sort_keys=True)
    copy_html_template('webedit.html', json_string, "REPLACEJSON")
    tab = webbrowser.open_new_tab(url)

    # This runs forever and can only be shut down in the handler or by 
    # ctr+c
    start_server(host=host, port=port, handler=WebEditHandler)

    try:
        obj = json.loads(
        	open_tmp_file('obj.json').readline(),
        	object_pairs_hook=OrderedDict)
    except:
        pass

    cleanup_tmp_folder()
    return obj 
Example #6
Source File: utils.py    From pygmt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def launch_external_viewer(fname):
    """
    Open a file in an external viewer program.

    Uses the ``xdg-open`` command on Linux, the ``open`` command on macOS, and
    the default web browser on other systems.

    Parameters
    ----------
    fname : str
        The file name of the file (preferably a full path).

    """
    # Redirect stdout and stderr to devnull so that the terminal isn't filled
    # with noise
    run_args = dict(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    # Open the file with the default viewer.
    # Fall back to the browser if can't recognize the operating system.
    if sys.platform.startswith("linux") and shutil.which("xdg-open"):
        subprocess.run(["xdg-open", fname], check=False, **run_args)
    elif sys.platform == "darwin":  # Darwin is macOS
        subprocess.run(["open", fname], check=False, **run_args)
    else:
        webbrowser.open_new_tab("file://{}".format(fname)) 
Example #7
Source File: base.py    From PyBloqs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 = self._id[:user_config["id_precision"]] + "." + 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 
Example #8
Source File: commands.py    From orthrus with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: wb_runner.py    From WhiteboxTools-ArcGIS with MIT License 6 votes vote down vote up
def tool_help_button(self):
        index = 0
        found = False
        #find toolbox corresponding to the current tool
        for toolbox in self.lower_toolboxes:
            for tool in self.sorted_tools[index]:
                if tool == self.tool_name:
                    self.toolbox_name = toolbox
                    found = True
                    break
            if found:
                break
            index = index + 1
        #change LiDAR to Lidar
        if index == 10:
            self.toolbox_name = to_camelcase(self.toolbox_name)
        #format subtoolboxes as for URLs
        self.toolbox_name = self.camel_to_snake(self.toolbox_name).replace('/', '').replace(' ', '') 
        #open the user manual section for the current tool
        webbrowser.open_new_tab("https://jblindsay.github.io/wbt_book/available_tools/" + self.toolbox_name + ".html#" + self.tool_name) 
Example #10
Source File: text_editor_hastebin.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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'} 
Example #11
Source File: debugger.py    From sublime_debugger with MIT License 6 votes vote down vote up
def on_settings(self) -> None:
		import webbrowser
		def about():
			webbrowser.open_new_tab("https://github.com/daveleroy/sublime_debugger/blob/master/docs/setup.md")
		
		def report_issue():
			webbrowser.open_new_tab("https://github.com/daveleroy/sublime_debugger/issues")

		values = Adapters.select_configuration(self).values
		values.extend([
			ui.InputListItem(lambda: ..., ""),
			ui.InputListItem(report_issue, "Report Issue"),
			ui.InputListItem(about, "About/Getting Started"),
		])

		ui.InputList(values).run() 
Example #12
Source File: terminal.py    From sublime_debugger with MIT License 6 votes vote down vote up
def click(self, text: str):
		values = [
			ui.InputListItem(lambda: sublime.set_clipboard(text), "Copy"),
		]
		for match in url_matching_regex.findall(text):
			values.insert(0, ui.InputListItem(lambda: webbrowser.open_new_tab(match[0]), "Open"))

		if self.clicked_menu:
			values[0].run()
			self.clicked_menu.cancel()
			return

		values[0].text += "\t Click again to select"

		self.clicked_menu = ui.InputList(values, text).run()
		await self.clicked_menu
		self.clicked_menu = None 
Example #13
Source File: editor.py    From DeTTECT with GNU General Public License v3.0 6 votes vote down vote up
def _run_webserver(self):
        """
        Starts the webserver on the given port.
        """
        try:
            os.chdir('./editor/dist')
            self.httpd = TCPServer(('', self.port), QuietHTTPRequestHandler)

            print("Editor started at port %d" % self.port)
            url = 'http://localhost:%d/dettect-editor' % self.port

            if not os.getenv('DeTTECT_DOCKER_CONTAINER'):
                print("Opening webbrowser: " + url)
                webbrowser.open_new_tab(url)
            else:
                print("You can open the Editor on: " + url)

            self.httpd.serve_forever()
        except Exception as e:
            print("Could not start webserver: " + str(e)) 
Example #14
Source File: RemarkableWindow.py    From Remarkable with MIT License 6 votes vote down vote up
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) 
Example #15
Source File: api.py    From wolfe with MIT License 6 votes vote down vote up
def stackoverflow(error):
  url = 'https://api.stackexchange.com/2.2/search/advanced?order=desc&migrated=False&sort=activity&body=%s&accepted=True&closed=False&site=stackoverflow&key=%s' % (error, key)
  try:
    response = requests.get(url, headers = headers)

    if response.status_code == 200:
      data = response.json()
      result_dict = []
      if len(data['items']) > 0:
        webbrowser.open_new_tab(data['items'][0]['link'])
        for i in range(1,min(6,len(data['items']))):
          res_dict = {}
          res_dict['title'] = data['items'][i]['title']
          res_dict['link'] = data['items'][i]['link']
          result_dict.append(res_dict)
        print tabulate([[i['title'][:50],i['link']] for i in result_dict], headers = ['Title','Link'],tablefmt="simple_grid")

      else:
        print "Substantial answers not found"
    else:
      print "Api Issues"
  except:
    print "Network Issues" 
Example #16
Source File: tasks.py    From callee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def docs(ctx, output='html', rebuild=False, show=True, verbose=True):
    """Build the docs and show them in default web browser."""
    sphinx_build = ctx.run(
        'sphinx-build -b {output} {all} {verbose} docs docs/_build'.format(
            output=output,
            all='-a -E' if rebuild else '',
            verbose='-v' if verbose else ''))
    if not sphinx_build.ok:
        fatal("Failed to build the docs", cause=sphinx_build)

    if show:
        path = os.path.join(DOCS_OUTPUT_DIR, 'index.html')
        if sys.platform == 'darwin':
            path = 'file://%s' % os.path.abspath(path)
        webbrowser.open_new_tab(path)


# TODO: remove this when PyPI upload from Travis CI is verified to work 
Example #17
Source File: systray.py    From p2ptv-pi with MIT License 5 votes vote down vote up
def OnStream(self, event = None):
        import webbrowser
        url = 'http://127.0.0.1:' + str(self.bgapp.httpport) + URLPATH_WEBIF_PREFIX + '/createstream'
        webbrowser.open_new_tab(url) 
Example #18
Source File: systray.py    From p2ptv-pi with MIT License 5 votes vote down vote up
def OnLeftClicked(self, event = None):
        if DEBUG:
            import webbrowser
            url = 'http://127.0.0.1:' + str(self.bgapp.httpport) + URLPATH_WEBIF_PREFIX
            webbrowser.open_new_tab(url) 
Example #19
Source File: twitch_plugin.py    From galaxy-plugin-twitch with GNU General Public License v3.0 5 votes vote down vote up
def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]:
        if not self._launcher_client.is_installed:
            webbrowser.open_new_tab("https://www.twitch.tv/downloads")
            raise InvalidCredentials

        def get_auth_info() -> Optional[Tuple[str, str]]:
            user_info = self._get_user_info()
            if not user_info:
                logging.warning("No user info")
                return None

            user_id = user_info.get("id")
            user_name = user_info.get("displayName")

            if not user_id or not user_name:
                logging.warning("No user id/name")
                return None

            return user_id, user_name

        auth_info = get_auth_info()
        if not auth_info:
            await self._launcher_client.start_launcher()
            raise InvalidCredentials

        self.store_credentials({"external-credentials": "force-reconnect-on-startup"})
        return Authentication(user_id=auth_info[0], user_name=auth_info[1]) 
Example #20
Source File: twitch_launcher_client.py    From galaxy-plugin-twitch with GNU General Public License v3.0 5 votes vote down vote up
def launch_game(self, game_id: str) -> None:
        if not self._is_launcher_running:
            await self.start_launcher()
            # even after launcher is started, we still have to wait some time, otherwise it ignores game launch commands
            await asyncio.sleep(3)

        webbrowser.open_new_tab(f"twitch://fuel-launch/{game_id}") 
Example #21
Source File: mapillary_api.py    From go2mapillary with GNU General Public License v3.0 5 votes vote down vote up
def browser(self,key):
        webbrowser.open_new_tab(BROWSER_ENDPOINT % key) 
Example #22
Source File: main_ui.py    From innstereo with GNU General Public License v2.0 5 votes vote down vote up
def on_menuitem_report_bug_activate(self, menuitem):
        # pylint: disable=unused-argument
        """
        This menuitem opens a new browser tab with the bug tracker.

        Triggered when the user clicks "Help -> Report a Bug" in the
        MenuBar.
        """
        webbrowser.open_new_tab(
            "https://github.com/innstereo/innstereo/issues") 
Example #23
Source File: main_ui.py    From innstereo with GNU General Public License v2.0 5 votes vote down vote up
def on_menuitem_website_activate(self, menuitem):
        # pylint: disable=unused-argument
        """
        This menuitem opens a new browser tab with the website of InnStereo.

        Triggered when the user clicks "Help -> Visit the Website" in the
        MenuBar.
        """
        webbrowser.open_new_tab(
                "http://innstereo.github.io/") 
Example #24
Source File: main_ui.py    From innstereo with GNU General Public License v2.0 5 votes vote down vote up
def on_menuitem_online_help_activate(self, menuitem):
        # pylint: disable=unused-argument
        """
        This menuitem opens a new browser tab with the online help.

        Triggered when the user clicks "Help -> View Online Help" in the
        MenuBar.
        """
        webbrowser.open_new_tab(
                        "http://innstereo.readthedocs.org") 
Example #25
Source File: Congratulations.py    From prog-o-meter with MIT License 5 votes vote down vote up
def open_facebook_browser(self):
        """Opens a new browser tab to the Facebook page for creating a post.

        Pre-populates the post with a stock message.
        """
        msg = quote("I just completed my " + str(self.challenge_duration) + "-days challenge! "+ self.challenge_hashtag)
        print(self.challenge_hashtag)
        print(msg)
        webbrowser.open_new_tab("https://www.facebook.com/sharer/sharer.php?u=https://github.com/prog-o-meter/prog-o-meter&quote=" + msg) 
Example #26
Source File: Congratulations.py    From prog-o-meter with MIT License 5 votes vote down vote up
def open_vk_browser(self):
        """Opens a new browser tab to the Vkontakte page for creating a post.

        Pre-populates the post with a stock message.
        """
        msg = quote("I just completed my " + str(self.challenge_duration) + "-days challenge! "+ self.challenge_hashtag)
        print(self.challenge_hashtag)
        print(msg)
        webbrowser.open_new_tab("https://vk.com/share.php?comment=" + msg) 
Example #27
Source File: test_monitoring_app.py    From estimagic with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_plot_time_series_with_large_initial_values():
    cds = ColumnDataSource({"y": [2e17, 1e16, 1e5], "x": [1, 2, 3]})
    title = "Are large initial values shown?"
    fig = monitoring._plot_time_series(data=cds, y_keys=["y"], x_name="x", title=title)
    title = "Test _plot_time_series can handle large initial values."
    output_file("time_series_initial_value.html", title=title)
    path = save(obj=fig)
    webbrowser.open_new_tab("file://" + path) 
Example #28
Source File: test_cmaps.py    From xcube with MIT License 5 votes vote down vote up
def main():
    cmaps = get_cmaps()

    html_head = '<!DOCTYPE html>\n' + \
                '<html lang="en">\n' + \
                '<head>' + \
                '<meta charset="UTF-8">' + \
                '<title>matplotlib Color Maps</title>' + \
                '</head>\n' + \
                '<body style="padding: 0.2em">\n'

    html_body = ''

    html_foot = '</body>\n' + \
                '</html>\n'

    for cmap_cat, cmap_desc, cmap_bars in cmaps:
        html_body += '    <h2>%s</h2>\n' % cmap_cat
        html_body += '    <p><i>%s</i></p>\n' % cmap_desc
        html_body += '    <table style=border: 0">\n'
        for cmap_bar in cmap_bars:
            cmap_name, cmap_data = cmap_bar
            cmap_image = '<img src="data:image/png;base64,%s" width="100%%" height="20px"/>' % cmap_data

            html_body += '        <tr><td style="width: 5em">%s:</td><td style="width: 40em">%s</td></tr>\n' % (
                cmap_name, cmap_image)
        html_body += '    </table>\n'

    html_page = html_head + html_body + html_foot

    html_filename = 'test_cmaps.html'
    with open(html_filename, 'w') as fp:
        fp.write(html_page)

    import webbrowser
    webbrowser.open_new_tab(html_filename) 
Example #29
Source File: RemarkableWindow.py    From Remarkable with MIT License 5 votes vote down vote up
def on_menuitem_donate_activate(self, widget):
        webbrowser.open_new_tab("http://remarkableapp.github.io/linux/donate")
 
    # Have disabled the check for updates function and also removed this choice from the About menu

    # def on_menuitem_check_for_updates_activate(self, widget):
    #     _thread.start_new_thread(self.check_for_updates, (True,))

    # def check_for_updates(self, show = False):
    #     try:
    #         update_check = urlopen("http://remarkableapp.github.io/latest")
    #         latest_version = float(update_check.readline())
    #         if app_version < latest_version:
    #             print("There is a new version avaiable")
    #             subprocess.Popen(['notify-send', "Remarkable: A new version of this app is avaiable"])
    #             update_check = urlopen("http://remarkableapp.github.io/change_log")
    #             md = update_check.read()
    #             html = markdown.markdown(md)
    #             if show:
    #                 webbrowser.open_new_tab("http://remarkableapp.github.io")
    #         else:
    #             if show:
    #                 subprocess.Popen(['notify-send', "Remarkable: You already have the latest version of this app available"])
    #                 print("You have the latest version of this app available")
    #     except:
    #         print("Warning: Remarkable could not connect to the internet to check for updates") 
Example #30
Source File: changelog.py    From sublime-boxy-theme with MIT License 5 votes vote down vote up
def on_navigate(self, href):
        webbrowser.open_new_tab(href)