python类open_new_tab()的实例源码

testing.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
util.py 文件源码 项目:SalesforceXyTools 作者: exiahuang 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
cli.py 文件源码 项目:pocket-cli 作者: rakanalh 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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'])
text_editor_hastebin.py 文件源码 项目:bpy_lambda 作者: bcongdon 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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'}
auth.py 文件源码 项目:flickr_downloader 作者: Denisolt 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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()
unit_tests.py 文件源码 项目:docusign-python-client 作者: docusign 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
pysession.py 文件源码 项目:pysession 作者: FallibleInc 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
hyper_click_command.py 文件源码 项目:SublimeHyperClick 作者: aziz 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
account.py 文件源码 项目:cli 作者: riseml 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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()
_graph_visualization.py 文件源码 项目:coremltools 作者: apple 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)))
RemarkableWindow.py 文件源码 项目:Remarkable 作者: jamiemcg 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
about.py 文件源码 项目:pyjam 作者: 10se1ucgo 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
testing.py 文件源码 项目:PYEdit 作者: Congren 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
cli.py 文件源码 项目:client 作者: wandb 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
base.py 文件源码 项目:PyBloqs 作者: manahl 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
commands.py 文件源码 项目:orthrus 作者: test-pipeline 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
Bookmark App.py 文件源码 项目:CleverProgrammerProjects 作者: ktsmpng 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
open_pygame_doc.py 文件源码 项目:st-user-package 作者: math2001 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
ToolTipHelper.py 文件源码 项目:ToolTip-Helper 作者: doobleweb 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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'
tugboat.py 文件源码 项目:scl_jamf_tools 作者: univ-of-utah-marriott-library-apple 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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.")
tugboat.py 文件源码 项目:scl_jamf_tools 作者: univ-of-utah-marriott-library-apple 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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.")
vi_actions.py 文件源码 项目:NeoVintageous 作者: NeoVintageous 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
cli.py 文件源码 项目:pocket-cli 作者: rakanalh 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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')
cli.py 文件源码 项目:pocket-cli 作者: rakanalh 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
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'])
pyoverflow.py 文件源码 项目:pyoverflow 作者: qboticslabs 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
tasks.py 文件源码 项目:django-include 作者: chrisseto 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 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')
ui_other.py 文件源码 项目:kaptan 作者: KaOSx 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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))"""
tab_config.py 文件源码 项目:EMFT 作者: 132nd-etcher 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _show_changelog():
        webbrowser.open_new_tab(constant.LINK_CHANGELOG)
browse_for_files.py 文件源码 项目:EMFT 作者: 132nd-etcher 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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()))
cherry_picker.py 文件源码 项目:core-workflow 作者: python 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号