Python webbrowser 模块,open_new() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用webbrowser.open_new()

项目:weibo    作者:windskyer    | 项目源码 | 文件源码
def token(self, CODE=''):
        client, url = self.getCODE()
        if not self.checked:
            if CODE == '':
                is_open = webbrowser.open_new(url)
                if not is_open:
                    LOG.info(_("Please use the browser to open %(url)s"),
                             {'url': url})
                try:
                    # for python2.x
                    CODE = raw_input(_("Please Input the Code: ")).strip()
                except:
                    # for python3.x
                    CODE = input(_("Please Input the Code: ")).strip()
            try:
                client.set_code(CODE)
            except:
                LOG.error(_("Maybe wrong CODE"))
                return
        token = client.token
        pkl.dump(token, open(str(self.token_file), 'wb'))
        self.api = Client(self.app_key,
                          self.app_secret,
                          self.callback_url, token)
        self.checked = True
项目:weibo    作者:windskyer    | 项目源码 | 文件源码
def token(self, CODE=''):
        client, url = self.getCODE()
        if self.checked == False:
            if CODE == '':
                import pdb;pdb.set_trace()
                is_open = webbrowser.open_new(url)
                if not is_open:
                    print('Please open %s' % url)
                try:
                    # for python2.x
                    CODE = raw_input("Please Input the Code: ").strip()
                except:
                    # for python3.x
                    CODE = input("Please Input the Code: ").strip()
            try:
                client.set_code(CODE)
            except:
                print("Maybe wrong CODE")
                return
        token = client.token
        pkl.dump(token, open(str(self.token_file), 'wb'))
        self.api = Client(self.APP_KEY, self.APP_SECRET, self.CALLBACK_URL, token)
        self.checked = True
项目:pib    作者:datawire    | 项目源码 | 文件源码
def handle_unexpected_errors(f):
    """Decorator that catches unexpected errors."""

    @wraps(f)
    def call_f(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception as e:
            errorf = StringIO()
            print_exc(file=errorf)
            error = errorf.getvalue()
            click.echo(
                "Looks like there's a bug in our code. Sorry about that!"
                " Here's the traceback:\n" + error)
            if click.confirm(
                    "Would you like to file an issue in our issue tracker?",
                    default=True, abort=True):
                url = "https://github.com/datawire/pib/issues/new?body="
                body = quote_plus(BUG_REPORT_TEMPLATE.format(
                    os.getcwd(), __version__, python_version,
                    run_result(["uname", "-a"]), error))
                webbrowser.open_new(url + body)

    return call_f
项目:Planet-GEE-Pipeline-GUI    作者:samapriya    | 项目源码 | 文件源码
def _request_refresh_token(self):
        # create configuration file dir
        config_dir = os.path.dirname(self._config_path)
        if not os.path.isdir(config_dir):
            os.makedirs(config_dir)

        # open browser and ask for authorization
        auth_request_url = gdal.GOA2GetAuthorizationURL(self._scope)
        print('Authorize access to your Fusion Tables, and paste the resulting code below: ' + auth_request_url)
        # webbrowser.open_new(auth_request_url)

        auth_code = raw_input('Please enter authorization code: ').strip()

        refresh_token = gdal.GOA2GetRefreshToken(auth_code, self._scope)

        # save it
        json.dump({'refresh_token': refresh_token}, open(self._config_path, 'w'))

        return refresh_token
项目:sublimeplugins    作者:ktuan89    | 项目源码 | 文件源码
def click(self, link):
        path = gitPath(self.view.window())
        command = ("cd '{0}';git show {1}").format(path, link)

        stdout, _ = run_bash_for_output(command)

        window = self.view.window()
        results_view = window.new_file()
        results_view.set_scratch(True)
        results_view.set_syntax_file('Packages/Diff/Diff.tmLanguage')

        results_view.set_name('GitBlame')

        # deps: this is from utilities.py
        results_view.run_command('replace_content', {"new_content": stdout})
        results_view.sel().clear()
        results_view.sel().add(sublime.Region(0, 0))

        window.focus_view(results_view)

        """for line in lines:
            matches = re.search(r'Differential Revision: (http.*/D[0-9]+)', line)
            if matches is not None:
                actual_link = matches.group(1)
                webbrowser.open_new(actual_link)"""
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def run(self, unused_args, unused_config):
    """Generates and opens a URL to get auth code, then retrieve a token."""

    auth_url = ee.oauth.get_authorization_url()
    webbrowser.open_new(auth_url)

    print("""
    Opening web browser to address %s
    Please authorize access to your Earth Engine account, and paste
    the resulting code below.
    If the web browser does not start, please manually browse the URL above.
          """ % auth_url)

    auth_code = input('Please enter authorization code: ').strip()

    token = ee.oauth.request_token(auth_code)
    ee.oauth.write_token(token)
    print('\nSuccessfully saved authorization token.')
项目:auxi.0    作者:Ex-Mente    | 项目源码 | 文件源码
def plot(self, dataset, path, show=False):
        with PdfPages(path) as pdf:
            x_vals = dataset.data['T'].tolist()
            y_vals = dataset.data[self.symbol].tolist()
            plt.plot(x_vals, y_vals, 'ro', alpha=0.4, markersize=4)

            x_vals2 = np.linspace(min(x_vals), max(x_vals), 80)
            fx = np.polyval(self._coeffs, x_vals2)
            plt.plot(x_vals2, fx, linewidth=0.3, label='')

            plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 4))
            plt.legend(loc=3, bbox_to_anchor=(0, 0.8))
            plt.title('$%s$ vs $T$' % self.display_symbol)
            plt.xlabel('$T$ (K)')

            plt.ylabel('$%s$ (%s)' % (self.display_symbol, self.units))

            fig = plt.gcf()
            pdf.savefig(fig)
            plt.close()

        if show:
            webbrowser.open_new(path)
项目:ecodash    作者:Servir-Mekong    | 项目源码 | 文件源码
def run(self, unused_args, unused_config):
    """Generates and opens a URL to get auth code, then retrieve a token."""

    auth_url = ee.oauth.get_authorization_url()
    webbrowser.open_new(auth_url)

    print """
    Opening web browser to address %s
    Please authorize access to your Earth Engine account, and paste
    the resulting code below.
    If the web browser does not start, please manually browse the URL above.
    """ % auth_url

    auth_code = raw_input('Please enter authorization code: ').strip()

    token = ee.oauth.request_token(auth_code)
    ee.oauth.write_token(token)
    print '\nSuccessfully saved authorization token.'
项目:Video-Downloader    作者:EvilCult    | 项目源码 | 文件源码
def __menu (self) :
        menubar = Tkinter.Menu(self.master)

        fileMenu = Tkinter.Menu(menubar, tearoff = 0)
        fileMenu.add_command(label = "Config", command = self.__configPanel)
        fileMenu.add_command(label = "Close", command = self.master.quit)
        menubar.add_cascade(label = "File", menu = fileMenu)

        aboutMenu = Tkinter.Menu(menubar, tearoff = 0)
        aboutMenu.add_command(label = "Info", command = self.__showInfo)
        aboutMenu.add_command(label = "Check Update", command = self.__chkUpdate)
        menubar.add_cascade(label = "About", menu = aboutMenu)

        helpMenu = Tkinter.Menu(menubar, tearoff = 0)
        helpMenu.add_command(label = "GitHub", command = lambda target = self.gitUrl : webbrowser.open_new(target))
        helpMenu.add_command(label = "Release Notes", command = lambda target = self.appUrl : webbrowser.open_new(target))
        helpMenu.add_command(label = "Send Feedback", command = lambda target = self.feedUrl : webbrowser.open_new(target))
        menubar.add_cascade(label = "Help", menu = helpMenu)

        self.master.config(menu = menubar)
项目:aqua-monitor    作者:Deltares    | 项目源码 | 文件源码
def run(self, unused_args, unused_config):
    """Generates and opens a URL to get auth code, then retrieve a token."""

    auth_url = ee.oauth.get_authorization_url()
    webbrowser.open_new(auth_url)

    print("""
    Opening web browser to address %s
    Please authorize access to your Earth Engine account, and paste
    the resulting code below.
    If the web browser does not start, please manually browse the URL above.
          """ % auth_url)

    auth_code = input('Please enter authorization code: ').strip()

    token = ee.oauth.request_token(auth_code)
    ee.oauth.write_token(token)
    print('\nSuccessfully saved authorization token.')
项目:SurfaceWaterTool    作者:Servir-Mekong    | 项目源码 | 文件源码
def run(self, unused_args, unused_config):
    """Generates and opens a URL to get auth code, then retrieve a token."""

    auth_url = ee.oauth.get_authorization_url()
    webbrowser.open_new(auth_url)

    print """
    Opening web browser to address %s
    Please authorize access to your Earth Engine account, and paste
    the resulting code below.
    If the web browser does not start, please manually browse the URL above.
    """ % auth_url

    auth_code = raw_input('Please enter authorization code: ').strip()

    token = ee.oauth.request_token(auth_code)
    ee.oauth.write_token(token)
    print '\nSuccessfully saved authorization token.'
项目:eb-deployment-boto-scripts    作者:coaic    | 项目源码 | 文件源码
def create_elastic_filesystem(region, vpc_id, private_subnets, security_group_id):
    print("""

    As Elastic File System is a relatively new service, API support is far from complete. You will need to create the file system
    in the AWS EFS Console. A browser window will open for you to create the file system. Several prompts from this script will
    guide you through the process.

    You will need to be already logged into the AWS Console on your browser.

    Ensure you select all listed availability zones.

    """)
    input("Ready to proceed? ")
    input(" Please note the VPC Id: %s, you will need to select this from wizard when it opens in the browser - ok? " %(vpc_id))
    input(" Please ensure you place this file system in the following subnets: %s - ok?" % (private_subnets))
    input(" Please also ensure the following security group is selected, in addition to the default security group: %s - ok?" % (security_group_id))
    webbrowser.open_new("https://%s.console.aws.amazon.com/efs/home?region=%s#/wizard/1" % (region, region))

    mount_point = input("Once you have completed the wizard please paste the mount point from the browser at the prompt: ")

    return mount_point

#
# Do VPC creation
#
项目:weight-watchers-sync    作者:Bachmann1234    | 项目源码 | 文件源码
def get_code(client_id):
    """
    Opens a browser so the user can give us the auth code
    Args:
        client_id (str): client id for the app we want to use
    Returns:
        str: auth code user provided
    """
    url = FITBIT_PERMISSION_SCREEN.format(
        client_id=client_id,
        scope='nutrition'
    )
    webbrowser.open_new(url)
    print(
        "I am attempting to get permission to run. "
        "A browser should have just opened. If it has not please go to {}".format(
            url
        )
    )
    return input(
        "A browser should have just opened: please provide the the text after 'code=' so I can continue: "
    )
项目:pw_Houdini_VEX_Editor    作者:paulwinex    | 项目源码 | 文件源码
def open_url_in_help_browser(self, url):
        print url
        if self.settings.get_value('use_external_browser', False):
            import webbrowser
            webbrowser.open_new(url)
        else:
            browser = [x for x in hou.ui.paneTabs() if x.type() == hou.paneTabType.HelpBrowser]
            if browser:
                browser = browser[0]
            else:
                desktop = hou.ui.curDesktop()
                browser = desktop.paneTabOfType(hou.paneTabType.HelpBrowser)
                if browser is None:
                    browser = desktop.createFloatingPane(hou.paneTabType.HelpBrowser)
            browser.setUrl(url)
            browser.setIsCurrentTab()
        QTimer.singleShot(200, self.focus_me)
项目:Netkeeper    作者:1941474711    | 项目源码 | 文件源码
def OnHelpEvent(self, event):
        webbrowser.open_new(C_APP_SITE)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def callback():
        webbrowser.open_new(r"http://www.google.com")
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def display_help():
    import webbrowser
    webbrowser.open_new("http://www.flyninja.net/book/?p=30")
项目:Fuxenpruefung    作者:andb0t    | 项目源码 | 文件源码
def callback_GitHub(event):
    webbrowser.open_new(r"https://github.com/andb0t/Fuxenpruefung")
项目:Fuxenpruefung    作者:andb0t    | 项目源码 | 文件源码
def callback_AGV(event):
    webbrowser.open_new(r"http://agv-muenchen.de/")
项目:Kivy-Dynamic-Screens-Template    作者:suchyDev    | 项目源码 | 文件源码
def on_enter(self, *args):
        super(ScreenWebView, self).on_enter(*args)
        if platform == 'android':
            ''' on android create webview for webpage '''
            self.ids["info_label"].text = "Please wait\nAttaching WebView"
            self.webview_lock = True
            Clock.schedule_once(self.create_webview, 0)         
        else:
            ''' on desktop just launch web browser '''
            self.ids["info_label"].text = "Please wait\nLaunching browser"
            import webbrowser
            webbrowser.open_new(self.url)
项目:Recruit    作者:Weiyanyu    | 项目源码 | 文件源码
def showItem(self):
        current_row = self.listWidget.currentRow()
        for i in range(current_row + 1):
            if i == current_row:
                url = self.staff_list[i].split(',')[1]
                webbrowser.open_new(url)


    #?????????
项目:weibo    作者:windskyer    | 项目源码 | 文件源码
def token(self, CODE=''):
        client, url = self.getCODE()
        if self.checked == False:
            if CODE == '':
                webbrowser.open_new(url)
                CODE = raw_input("Please Input the Code: ").strip()
            try:
                client.set_code(CODE)
            except:
                print "Maybe wrong CODE"
                return
        token = client.token
        pkl.dump(token, file(self.token_file, 'w'))
        self.api = Client(self.APP_KEY, self.APP_SECRET, self.CALLBACK_URL, token)
        self.checked = True
项目:KodiDevKit    作者:phil65    | 项目源码 | 文件源码
def go_to_help(self, word):
        """
        open browser and go to wiki page for control with type *word
        """
        webbrowser.open_new(self.CONTROLS[word])
项目:Easy-Bookmark-Accessing    作者:gokuSSJ95    | 项目源码 | 文件源码
def authFunc(fd,q): # Opens the desired bookmark.
    if q>=1 and q<=len(fd):
        webbrowser.open_new(fd[q-1]["url"])
    else:
        print("Invalid input.")
        q = int(input("Enter a valid result no. to be opened: "))
        authFunc(fd,q)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def show_control_web(self, widget=None, data=None):
        host_port = config.get(["modules", "launcher", "control_port"], 8085)
        webbrowser.open_new("http://127.0.0.1:%s/" % host_port)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def config_(self, notification):
        host_port = config.get(["modules", "launcher", "control_port"], 8085)
        webbrowser.open_new("http://127.0.0.1:%s/" % host_port)
项目:Alphaman    作者:Changsung    | 项目源码 | 文件源码
def run(self):
        while self.notResponding():
            print('Did not respond')
        print('Responded')
        webbrowser.open_new('http://127.0.0.1:8888/')
项目:siren    作者:ozsolarwind    | 项目源码 | 文件源码
def showHelp(self):
        webbrowser.open_new(self.help)
项目:siren    作者:ozsolarwind    | 项目源码 | 文件源码
def showHelp(self):
        if self.leave_help_open:
            webbrowser.open_new(self.helpfile)
        else:
            dialog = displayobject.AnObject(QtGui.QDialog(), self.helpfile, title='Help')
            dialog.exec_()
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def show_control_web(self, widget=None, data=None):
        host_port = config.get(["modules", "launcher", "control_port"], 8085)
        webbrowser.open_new("http://127.0.0.1:%s/" % host_port)
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def config_(self, notification):
        host_port = config.get(["modules", "launcher", "control_port"], 8085)
        webbrowser.open_new("http://127.0.0.1:%s/" % host_port)
项目:WPEAR    作者:stephenlienharrell    | 项目源码 | 文件源码
def showWebsite(self):
    #webbrowser.open_new(self.landing_file)
    pass
项目:sublimeplugins    作者:ktuan89    | 项目源码 | 文件源码
def run(self, edit):
        path = gitPath(self.view.window())
        current_path = self.view.file_name()
        if current_path is not None and current_path.startswith(path) and gitWebBlameUrl() is not None:
            remaining_path = current_path[len(path):]
            print(remaining_path,' ', current_path, ' ', path)
            link = gitWebBlameUrl().format(remaining_path)
            webbrowser.open_new(link)
项目:K40-Whisperer    作者:jkramarz    | 项目源码 | 文件源码
def menu_Help_Web(self):
        webbrowser.open_new(r"http://www.scorchworks.com/K40whisperer/k40whisperer.html")
项目:Solfege    作者:RannyeriDev    | 项目源码 | 文件源码
def handle_href(self, href):
        u = urlparse(href)
        if u.scheme:
            try:
                webbrowser.open_new(href)
            except Exception, e:
                solfege.win.display_error_message2(_("Error opening web browser"), str(e))

        else:
            solfege.win.display_docfile(u.path)
项目:Solfege    作者:RannyeriDev    | 项目源码 | 文件源码
def show_bug_reports(self, *v):
        m = Gtk.Dialog(_("Question"), self, 0)
        m.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
        m.add_button(Gtk.STOCK_OK, Gtk.ResponseType.OK)
        vbox = Gtk.VBox()
        m.vbox.pack_start(vbox, False, False, 0)
        vbox.set_spacing(18)
        vbox.set_border_width(12)
        l = Gtk.Label(label=_("Please enter the email used when you submitted the bugs:"))
        vbox.pack_start(l, False, False, 0)
        self.g_email = Gtk.Entry()
        m.action_area.get_children()[0].grab_default()
        self.g_email.set_activates_default(True)
        vbox.pack_start(self.g_email, False, False, 0)
        m.show_all()
        ret = m.run()
        m.destroy()
        if ret == Gtk.ResponseType.OK:
            params = urllib.urlencode({
                    'pagename': 'SITS-Incoming/SearchBugs',
                    'q': 'SITS-Incoming/"Submitter: %s"' % utils.mangle_email(self.g_email.get_text().decode("utf-8")()),
                })
            try:
                webbrowser.open_new("http://www.solfege.org?%s" % params)
            except Exception, e:
                self.display_error_message2(_("Error opening web browser"), str(e))
项目:docphp    作者:garveen    | 项目源码 | 文件源码
def on_navigate(self, url):
        if re.search('^https?://', url):
            webbrowser.open_new(url)
            return True

        m = re.search('^(changeto|constant)\.(.*)', url)
        if m:
            if m.group(1) == 'changeto':
                symbol, content = getSymbolDescription(self.currentSymbol, m.group(2))
            else:
                self.view.run_command('docphp_insert', {"string": m.group(2)})
                self.view.hide_popup()

        elif url == 'history.back':
            symbol = self.history.pop()
            self.currentSymbol = symbol
        else:
            self.history.append(self.currentSymbol)
            symbol = url[:url.find('.html')]
            self.currentSymbol = symbol
        symbol, content = getSymbolDescription(symbol)

        if content == False:
            return False

        content = self.formatPopup(content, symbol=symbol, can_back=len(self.history) > 0)

        content = content[:65535]
        self.view.update_popup(content)
项目:Beginners-Python-Examples    作者:AsciiKay    | 项目源码 | 文件源码
def alarm(h,m,s):
    timeToSleep = h * 3600 + m * 60 + s
    sleepingTime = sleep(timeToSleep)
    playSound = webbrowser.open_new(random.choice(linksToSounds))

# Main code
项目:Beginners-Python-Examples    作者:AsciiKay    | 项目源码 | 文件源码
def timer(minutes):
    a = 0
    while a != minutes: 
        time.sleep(59)
        a = a + 1
    print("<<<<<<Timed out>>>>>>")  
    # I have not used return cause it termites the function
    webbrowser.open_new("https://www.youtube.com/watch?v=SlZMVAydqaE")
项目:auxi.0    作者:Ex-Mente    | 项目源码 | 文件源码
def create_template(material, path, show=False):
        """
        Create a template csv file for a data set.

        :param material: the name of the material
        :param path: the path of the directory where the file must be written
        :param show: a boolean indicating whether the created file should be \
        displayed after creation
        """
        file_name = 'dataset-%s.csv' % material.lower()
        file_path = os.path.join(path, file_name)

        with open(file_path, 'w', newline='') as csvfile:
            writer = csv.writer(csvfile, delimiter=',',
                                quotechar='"', quoting=csv.QUOTE_MINIMAL)
            writer.writerow(['Name', material])
            writer.writerow(['Description', '<Add a data set description '
                                            'here.>'])
            writer.writerow(['Reference', '<Add a reference to the source of '
                                          'the data set here.>'])
            writer.writerow(['Temperature', '<parameter 1 name>',
                            '<parameter 2 name>', '<parameter 3 name>'])
            writer.writerow(['T', '<parameter 1 display symbol>',
                             '<parameter 2 display symbol>',
                             '<parameter 3 display symbol>'])
            writer.writerow(['K', '<parameter 1 units>',
                             '<parameter 2 units>', '<parameter 3 units>'])
            writer.writerow(['T', '<parameter 1 symbol>',
                             '<parameter 2 symbol>', '<parameter 3 symbol>'])
            for i in range(10):
                writer.writerow([100.0 + i*50, float(i), 10.0 + i, 100.0 + i])

        if show is True:
            webbrowser.open_new(file_path)
项目:seu-jwc-catcher    作者:LeonidasCl    | 项目源码 | 文件源码
def click_about(text):
    print("You clicked '%s'" % text)
    webbrowser.open_new(text)
项目:seu-jwc-catcher    作者:LeonidasCl    | 项目源码 | 文件源码
def check_table():
    global username
    dialog = Toplevel(root)
    dialog.geometry('240x100+360+300')
    dialog.title('?????')
    Label(dialog, text="??????????????16-17-2").pack()
    v = StringVar()
    Entry(dialog,textvariable=v).pack(pady=5)
    Button(dialog, text=' ???? ', command=lambda: webbrowser.open_new(r"http://xk.urp.seu.edu.cn/jw_s"
                                                                      r"ervice/service/stuCurriculum.action?queryStudentId=" + str(
        username) + "&queryAcademicYear=" + v.get())).pack(pady=5)
项目:python-scripts    作者:TheKetan2    | 项目源码 | 文件源码
def callback(event):
    webbrowser.open_new("http://www.github.com/theketan2")
项目:Manimouse    作者:shivamkajale    | 项目源码 | 文件源码
def OpenDoc():
    wb.open_new('https://drive.google.com/open?id=1Wi6vTs4UpHZIsDLA-S_BWiwHK9TuY-w4TFQfpT5UlFw')
    return 0
项目:Manimouse    作者:shivamkajale    | 项目源码 | 文件源码
def OpenCredits():
    wb.open_new('https://drive.google.com/open?id=0BzMlLgwt8GfyT0NmZjlUWFpQaVE')
    return 0
项目:Manimouse    作者:shivamkajale    | 项目源码 | 文件源码
def OpenHelp():
    wb.open_new('https://drive.google.com/open?id=0BzMlLgwt8GfyTW9tRnJTWUhWaUU')
    return 0
项目:Manimouse    作者:shivamkajale    | 项目源码 | 文件源码
def OpenDoc():
    wb.open_new('https://drive.google.com/open?id=1Wi6vTs4UpHZIsDLA-S_BWiwHK9TuY-w4TFQfpT5UlFw')
    return 0
项目:Manimouse    作者:shivamkajale    | 项目源码 | 文件源码
def OpenCredits():
    wb.open_new('https://drive.google.com/open?id=0BzMlLgwt8GfyT0NmZjlUWFpQaVE')
    return 0
项目:f-engrave    作者:stephenhouser    | 项目源码 | 文件源码
def menu_Help_Web(self):
        webbrowser.open_new(r"http://www.scorchworks.com/Fengrave/fengrave_doc.html")
项目:f-engrave    作者:stephenhouser    | 项目源码 | 文件源码
def menu_Help_Web(self):
        webbrowser.open_new(r"http://www.scorchworks.com/Fengrave/fengrave_doc.html")