Python webbrowser.open_new_tab() Examples

The following are 30 code examples for showing how to use webbrowser.open_new_tab(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module webbrowser , or try the search function .

Example 1
Project: SalesforceXyTools   Author: exiahuang   File: util.py    License: 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 2
Project: awe   Author: dankilman   File: page.py    License: 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 3
Project: azure-cli-extensions   Author: Azure   File: custom.py    License: 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 4
Project: SalesforceXyTools   Author: exiahuang   File: util.py    License: Apache License 2.0 6 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 5
Project: Remarkable   Author: jamiemcg   File: RemarkableWindow.py    License: 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 6
Project: orthrus   Author: test-pipeline   File: commands.py    License: 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 7
Project: callee   Author: Xion   File: tasks.py    License: 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 8
Project: wolfe   Author: h4ck3rk3y   File: api.py    License: 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 9
Project: DeTTECT   Author: rabobank-cdc   File: editor.py    License: 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 10
Project: sublime_debugger   Author: daveleroy   File: terminal.py    License: 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 11
Project: sublime_debugger   Author: daveleroy   File: debugger.py    License: 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
Project: Fluid-Designer   Author: Microvellum   File: text_editor_hastebin.py    License: 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 13
Project: WhiteboxTools-ArcGIS   Author: giswqs   File: wb_runner.py    License: 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 14
Project: quantipy   Author: Quantipy   File: servers.py    License: 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 15
Project: PyBloqs   Author: man-group   File: base.py    License: 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 16
Project: pygmt   Author: GenericMappingTools   File: utils.py    License: 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 17
Project: multibootusb   Author: mbusb   File: mbusb_gui.py    License: GNU General Public License v2.0 5 votes vote down vote up
def onAboutClick(self):
        about = QtWidgets.QDialog()
        about.ui = Ui_About()
        about.ui.setupUi(about)
        about.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        about.setWindowTitle("About MultiBootUSB - " + mbusb_version())
        about.setWindowIcon(QtGui.QIcon(resource_path(os.path.join("data", "tools", "multibootusb.png"))))
        about.ui.button_close.clicked.connect(about.close)
        about.ui.label_6.linkActivated.connect(webbrowser.open_new_tab)
        about.exec_() 
Example 18
Project: PickTrue   Author: winkidney   File: __main__.py    License: MIT License 5 votes vote down vote up
def open_online_help():
        url = 'https://github.com/winkidney/PickTrue'
        webbrowser.open_new_tab(url) 
Example 19
Project: PickTrue   Author: winkidney   File: __main__.py    License: MIT License 5 votes vote down vote up
def show_about():
        webbrowser.open_new_tab(
            'https://winkidney.com'
        ) 
Example 20
Project: WiCC   Author: pabloibiza   File: wicc_view_about.py    License: GNU General Public License v3.0 5 votes vote down vote up
def open_link(event):
        """
        Opens the URL on a new tab in the default web browser.

        :author: Pablo Sanz Alguacil
        """

        url = "http://www.github.com/pabloibiza/WiCC"
        webbrowser.open_new_tab(url) 
Example 21
Project: WiCC   Author: pabloibiza   File: wicc_view.py    License: GNU General Public License v3.0 5 votes vote down vote up
def open_link(self):
        """
        Opens the URL on a new tab in the default web browser.

        :author: Pablo Sanz Alguacil
        """

        url = "http://www.github.com/pabloibiza/WiCC"
        webbrowser.open_new_tab(url) 
Example 22
Project: pyhanlp   Author: hankcs   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def browser_open(url):
    option = input('是否前往 {} ?(y/n)'.format(url)).lower()
    if option in ('y', 'yes', '是'):
        import webbrowser
        webbrowser.open_new_tab(url) 
Example 23
Project: reqman   Author: manatlan   File: conftest.py    License: GNU General Public License v2.0 5 votes vote down vote up
def view(self):
        h=tempfile.mktemp()+".html"
        with open(h,"w+") as fid:
            ansi_escape =re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]')
            console=ansi_escape.sub('', self.console)    
            fid.write("""<h3>Test file : "%s"</h3>""" % os.getenv('PYTEST_CURRENT_TEST') )
            fid.write("""<h3>RC : %s <-- "%s"</h3>""" % (self.rc," ".join(sys.argv)))
            fid.write("""<h3>Output Console:</h3><pre>%s</pre>""" % html.escape(console))
            if self.rr:
                fid.write("""<h3>Env:</h3><pre>%s</pre>""" % (json.dumps(self.rr.env, indent=4, sort_keys=True)))
                fid.write("""<h3>Output Html (%s):</h3>%s""" % (self.rr.__class__.__name__,self.rr.html))
            
        import webbrowser
        webbrowser.open_new_tab(h) 
Example 24
Project: dephell   Author: dephell   File: package_bug.py    License: MIT License 5 votes vote down vote up
def __call__(self) -> bool:
        dep = get_package(self.args.name, repo=self.config.get('repo'))
        dep.repo.get_releases(dep)  # fetch metainfo
        url = self._get_url(links=dep.links)
        if not url:
            self.logger.error('cannot find bug tracker URL')
            return False
        webbrowser.open_new_tab(url=url)
        return True 
Example 25
Project: RAASNet   Author: leonv024   File: RAASNet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def open_github(self):
        webbrowser.open_new_tab('https://www.github.com/leonv024/RAASNet') 
Example 26
Project: RAASNet   Author: leonv024   File: RAASNet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def open_buy(self):
        webbrowser.open_new_tab('https://www.zeznzo.nl/') 
Example 27
Project: mars   Author: mars-project   File: core.py    License: Apache License 2.0 5 votes vote down vote up
def new_cluster(address='0.0.0.0', web=False, n_process=None, shared_memory=None,
                open_browser=None, **kw):
    open_browser = open_browser if open_browser is not None else options.deploy.open_browser
    endpoint = gen_endpoint(address)
    web_endpoint = None
    if web is True:
        web_endpoint = gen_endpoint('0.0.0.0')
    elif isinstance(web, str):
        if ':' in web:
            web_endpoint = web
        else:
            web_endpoint = gen_endpoint(web)

    process = _start_cluster_process(endpoint, n_process, shared_memory, **kw)

    web_process = None
    if web_endpoint:
        web_process = _start_web_process(endpoint, web_endpoint)
        print('Web endpoint started at http://%s' % web_endpoint, file=sys.stderr)
        if open_browser:
            import webbrowser
            webbrowser.open_new_tab('http://%s' % web_endpoint)

    client = LocalDistributedClusterClient(endpoint, web_endpoint, process, web_process)
    _local_cluster_clients[id(client)] = client
    return client 
Example 28
Project: flask-apispec   Author: jmcarp   File: tasks.py    License: MIT License 5 votes vote down vote up
def browse_docs(ctx):
    path = os.path.join(build_dir, 'index.html')
    webbrowser.open_new_tab(path) 
Example 29
Project: flask-apispec   Author: jmcarp   File: tasks.py    License: MIT License 5 votes vote down vote up
def readme(ctx, browse=False):
    ctx.run("rst2html.py README.rst > README.html")
    if browse:
        webbrowser.open_new_tab('README.html') 
Example 30
Project: azure-cli-extensions   Author: Azure   File: custom.py    License: MIT License 5 votes vote down vote up
def wait_then_open(url):
    """
    Waits for a bit then opens a URL.  Useful for waiting for a proxy to come up, and then open the URL.
    """
    for _ in range(1, 10):
        try:
            urlopen(url, context=_ssl_context())
        except URLError:
            time.sleep(1)
        break
    webbrowser.open_new_tab(url)