• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python webbrowser.open函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中webbrowser.open函数的典型用法代码示例。如果您正苦于以下问题:Python open函数的具体用法?Python open怎么用?Python open使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了open函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: main

def main():
    # change path to launcher
    global __file__
    __file__ = os.path.abspath(__file__)
    if os.path.islink(__file__):
        __file__ = getattr(os, 'readlink', lambda x: x)(__file__)
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    launcher_log.info("start XX-Net %s", update_from_github.current_version())

    web_control.confirm_xxnet_exit()

    setup_win_python.check_setup()

    module_init.start_all_auto()

    web_control.start()


    if has_desktop and config.get(["modules", "launcher", "popup_webui"], 1) == 1:
        host_port = config.get(["modules", "launcher", "control_port"], 8085)
        webbrowser.open("http://127.0.0.1:%s/" % host_port)

    update.start()

    if config.get(["modules", "launcher", "show_systray"], 1):
        sys_tray.serve_forever()
    else:
        while True:
            time.sleep(100)

    module_init.stop_all()
    sys.exit()
开发者ID:guoyunliang,项目名称:XX-Net,代码行数:33,代码来源:start.py


示例2: open_location

    def open_location(self, locations):
        """
        Try to open one of the specified locations in a new window of the default
        browser. See webbrowser module for more information.

        locations should be a tuple.
        """
        # CB: could have been a list. This is only here because if locations is set
        # to a string, it will loop over the characters of the string.
        assert isinstance(locations,tuple),"locations must be a tuple."

        for location in locations:
            try:
                existing_location = resolve_path(location)
                webbrowser.open(existing_location,new=2,autoraise=True)
                self.messageBar.response('Opened local file '+existing_location+' in browser.')
                return ###
            except:
                pass

        for location in locations:
            if location.startswith('http'):
                try:
                    webbrowser.open(location,new=2,autoraise=True)
                    self.messageBar.response('Opened remote location '+location+' in browser.')
                    return ###
                except:
                    pass

        self.messageBar.response("Could not open any of %s in a browser."%locations)
开发者ID:AnthonyAlers,项目名称:topographica,代码行数:30,代码来源:topoconsole.py


示例3: handle

def handle(text, mic, profile):
    baseurl= "http://www.wikihow.com/"
    wiki = MediaWiki('http://www.wikihow.com/api.php')
    #wiki.login("[email protected]", "david1234")
    params = {'action':'query','list':'search','srsearch':text,'srprop':'redirecttitle','limit':'1', 'format':'json'}

    response = wiki.call(params)
    #r = json.dumps(response, sort_keys=True, indent=4, separators=(',', ': '))

    flag = 0
    flag_title = "none"
    pos= response['query']['search']
    query = getRequest(text)
    wiki.logout()
#Getting the article with the best score
    for key in pos:
        val = fuzz.ratio(key['title'],query)
        print(str(val) + "% " + key['title'])
        if val > flag:
            flag = val
            flag_title = key['title']
    if flag !=0:
        answer = flag_title
        mic.say(answer)

        #rWH = renderWH.renderWikihow()
        #url = baseurl + answer
        #print url
        #url_ = rWH.getContent(str(url))
        #rWH.renderContent(url_)
        webbrowser.open(baseurl + flag_title)
    else:
        mic.say("I could not find anything bro!")
开发者ID:weemill,项目名称:gyro_jasper,代码行数:33,代码来源:howto.py


示例4: open_websession

    def open_websession(self):
        """
        Open a web browser session to prompt the user to authenticate via their
        AAD credentials.
        This method of authentication is the 'last resort' after
        auto-authentication and unattended authentication have failed.

        :Raises:
            - :class:`RuntimeError` if authentication fails, which will fail
              the loading of the addon as all auth routes have failed. This
              could be due to either an 
              :class:`batchapps.exceptions.AuthenticationException` of a
              :class:`batchapps.exceptions.InvalidConfigException`.
        """
        session = bpy.context.scene.batchapps_session

        try:
            url, state = AzureOAuth.get_authorization_url(config=session.cfg)
            webbrowser.open(url)

            session.log.info("Opened web browser for authentication "
                             "and waiting for response.")

            self.wait_for_request()

        except (AuthenticationException, InvalidConfigException) as exp:
            session.log.error("Unable to open Web UI auth session: "
                              "{0}".format(exp))

            raise RuntimeError("Failed to authorize addon")
开发者ID:ComanGamesStudio,项目名称:azure-batch-apps-blender,代码行数:30,代码来源:auth.py


示例5: gdb

def gdb(scripts_filename, fields, view, new):
    """
    Debug-print trees from stdin and either write HTML to stdout or open in
    browser.

    scripts_filename: path to scripts
    fields: CoNLL fields to print in trees
    view: if True, open in browser, otherwise print HTML to stdout
    new: if True, don't try to reuse old browser tabs (when viewing)
    """

    # If need not view in browser, write HTML to stdout.
    if not view:
        _gdb(scripts_filename, fields, file=sys.stdout)
        return

    # Create temporary file.
    f = tempfile.NamedTemporaryFile(delete=False, suffix='.html')
    filename = f.name
    f.close()

    # Write HTML to temporary file.
    with codecs.open(filename, 'wb', encoding='utf-8') as f:
        _gdb(scripts_filename, fields, file=f)

    # Open that file.
    webbrowser.open('file://' + filename, new=new*2)
开发者ID:yandex,项目名称:dep_tregex,代码行数:27,代码来源:__main__.py


示例6: browse_remote

def browse_remote(pep):
    import webbrowser
    file = find_pep(pep)
    if file.startswith('pep-') and file.endswith((".txt", '.rst')):
        file = file[:-3] + "html"
    url = PEPDIRRUL + file
    webbrowser.open(url)
开发者ID:ericsnowcurrently,项目名称:peps,代码行数:7,代码来源:pep2html.py


示例7: setSource

 def setSource(self, url):
     """Called when user clicks on a URL"""
     name = unicode(url.toString())
     if name.startswith(u'http'):
         webbrowser.open(name, True)
     else:
         QtGui.QTextBrowser.setSource(self, QtCore.QUrl(name))
开发者ID:BackupTheBerlios,项目名称:convertall-svn,代码行数:7,代码来源:helpview.py


示例8: open_url

def open_url(url, quiet = True):
    try:
        webbrowser.open(url)
    except webbrowser.Error as ex: 
        log.error('Failed to open URL "{0}" in default browser, because "{1}".'.format(url, ex))
        if not quiet:
            raise
开发者ID:Gbuomprisco,项目名称:step-elastic-beanstalk-deploy,代码行数:7,代码来源:shell_utils.py


示例9: main

def main():
  parser = Parser()

  # Parse the input files.
  for src in FLAGS.sources:
    if src == '-':
      parser.parse_file(sys.stdin)
    else:
      with open(src, mode='r') as infile:
        parser.parse_file(infile)

  # Print the csv.
  if not FLAGS.open:
    parser.print_csv()
  else:
    dirname = tempfile.mkdtemp()
    basename = FLAGS.name
    if os.path.splitext(basename)[1] != '.csv':
      basename += '.csv';
    pathname = os.path.join(dirname, basename)
    with open(pathname, mode='w') as tmpfile:
      parser.print_csv(outfile=tmpfile)
    fileuri = urlparse.urljoin('file:', urllib.pathname2url(pathname))
    print('opening %s' % fileuri)
    webbrowser.open(fileuri)
开发者ID:MIPS,项目名称:external-skia,代码行数:25,代码来源:sheet.py


示例10: process_html

def process_html(htmlPart):
    # Example using BeautifulSoup
    #soup = BeautifulSoup(htmlPart.get_payload(decode=True))
    #for link in soup.findAll('a'):
    #   if link['href']:
    #       url = link['href']

    # BeautifulSoup is a better way to extract links, but isn't
    # guaranteed to be installed. Use custom HTMLParser class instead.
    parser = UrlParser()
    parser.feed(htmlPart.get_payload(decode=True))
    parser.close()
    urls = parser.get_urls()

    if any(urls):
        for url in urls:
            logging.info("!!! Found a URL: " + url)
            # Attempt to open the url in the default browser
            # Use a new window to de-conflict other potential exploits
            # new=0 -> same window
            # new=1 -> new window
            # new=2 -> new tab
            logging.debug("Opening URL " + url)
            webbrowser.open(url, 1)

    filename = htmlPart.get_filename()
    if filename:
        # We have an HTML attachment
        # Attempt to save and open it.
        process_attachment(htmlPart, '.html')
开发者ID:former1610,项目名称:email-checker,代码行数:30,代码来源:email-checker.py


示例11: goURL

    def goURL(self, event):
	try:
	    webbrowser.open(self.noteDescrip.GetValue())
	except:
	    dial = wx.MessageDialog(None, 'Unable to launch internet browser', 'Error', wx.OK | wx.ICON_ERROR)
	    dial.ShowModal()  
	    return
开发者ID:imtiazKHAN,项目名称:ProtocolNavigator,代码行数:7,代码来源:notepad.py


示例12: info_command

def info_command():
  i = listbox.curselection()
  try:
    item = listbox.get(i)
  except Tkinter.TclError:
    return
  webbrowser.open("http://en.wikipedia.org/wiki/%s" % armor(item))
开发者ID:philetus,项目名称:molecule_graph_matcher,代码行数:7,代码来源:PyMolGui.py


示例13: test_access_token_acquisition

    def test_access_token_acquisition(self):
        """
        This test is commented out because it needs user-interaction.
        """
        if not self.RUN_INTERACTIVE_TESTS:
            return
        oauth_authenticator = scapi.authentication.OAuthAuthenticator(self.CONSUMER, 
                                                                      self.CONSUMER_SECRET,
                                                                      None, 
                                                                      None)

        sca = scapi.ApiConnector(host=self.API_HOST, authenticator=oauth_authenticator)
        token, secret = sca.fetch_request_token()
        authorization_url = sca.get_request_token_authorization_url(token)
        webbrowser.open(authorization_url)
        oauth_verifier = raw_input("please enter verifier code as seen in the browser:")
        
        oauth_authenticator = scapi.authentication.OAuthAuthenticator(self.CONSUMER, 
                                                                      self.CONSUMER_SECRET,
                                                                      token, 
                                                                      secret)

        sca = scapi.ApiConnector(self.API_HOST, authenticator=oauth_authenticator)
        token, secret = sca.fetch_access_token(oauth_verifier)
        logger.info("Access token: '%s'", token)
        logger.info("Access token secret: '%s'", secret)
        # force oauth-authentication with the new parameters, and
        # then invoke some simple test
        self.AUTHENTICATOR = "oauth"
        self.TOKEN = token
        self.SECRET = secret
        self.test_connect()
开发者ID:jdunck,项目名称:python-api-wrapper,代码行数:32,代码来源:scapi_tests.py


示例14: on_navigation_policy

 def on_navigation_policy(self, webview, frame, request, action, decision):
     uri = request.get_uri()
     if not uri.startswith('gir://'):
         webbrowser.open(uri)
         decision.ignore()
         return True
     parts = uri.split('/')[2:]
     gir = parts.pop(0)
     if gir:
         for namespace in self.get_namespaces():
             if namespace.name == gir:
                 self._set_namespace(namespace)
                 if not parts:
                     self._show_namespace(namespace)
                     decision.ignore()
                     return True
                 break
         name = parts.pop(0) if parts else None
         if name:
             for klass in namespace.classes:
                 if name == klass.name:
                     self._set_class(klass)
                     if not parts:
                         self._show_class(namespace, klass)
                         decision.ignore()
                         return True
     return False
开发者ID:chergert,项目名称:gobject-introspect-doc,代码行数:27,代码来源:win.py


示例15: inner_run

 def inner_run():
     print "Validating models..."
     self.validate(display_num_errors=True)
     print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
     print "Development server is running at http://%s:%s/" % (addr, port)
     print "Using the Werkzeug debugger (http://werkzeug.pocoo.org/)"
     print "Quit the server with %s." % quit_command
     path = options.get('admin_media_path', '')
     if not path:
         admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin')
         if os.path.isdir(admin_media_path):
             path = admin_media_path
         else:
             path = os.path.join(django.__path__[0], 'contrib/admin/media')
     handler = WSGIHandler()
     if USE_ADMINMEDIAHANDLER:
         handler = AdminMediaHandler(handler, path)
     if USE_STATICFILES:
         use_static_handler = options.get('use_static_handler', True)
         insecure_serving = options.get('insecure_serving', False)
         if use_static_handler and (settings.DEBUG or insecure_serving):
             handler = StaticFilesHandler(handler)
     if open_browser:
         import webbrowser
         url = "http://%s:%s/" % (addr, port)
         webbrowser.open(url)
     run_simple(addr, int(port), DebuggedApplication(handler, True),
                use_reloader=use_reloader, use_debugger=True, threaded=threaded)
开发者ID:2flcastro,项目名称:ka-lite,代码行数:28,代码来源:runserver_plus.py


示例16: link

 def link(self, event):
     "opens browser with linked page"
     link = "http://www.gnu.org/licenses/gpl-3.0.html"
     try:
         webbrowser.open(link)
     except Exception:
         self.bell()
开发者ID:bahniks,项目名称:CM_Manager_0_4_0,代码行数:7,代码来源:menu.py


示例17: do_args

def do_args(arg, quoted_output, output):
  if not quoted_output:
    cmd = '{}://x-callback-url/'.format(arg)
  else:
    if arg == 'onewriter':
      # Replace 'Notepad.txt' with the name of your open doc in 1Writer
      cmd = '{}://x-callback-url/append?path=Documents%2F&name=Notepad.txt&type=Local&text={}'.format(arg, quoted_output)
    if arg == 'editorial':
      clipboard.set(output)
      '''
      'Append Open Doc' is an Editorial workflow
      available here:
      http://www.editorial-workflows.com/workflow/5278032428269568/g2tYM1p0OZ4
      '''
      cmd = '{}://?command=Append%20Open%20Doc'.format(arg)
    if arg == 'drafts4':
      '''
      Append gps data to open Draft doc using the
      2nd argument from calling URL as the UUID of
      the open doc
      '''
      cmd = '{}://x-callback-url/append?uuid={}&text={}'.format(arg, sys.argv[2], quoted_output)

  webbrowser.open(cmd)
  sys.exit('Finished!')
开发者ID:c0ns0le,项目名称:Pythonista,代码行数:25,代码来源:SendGpsData.py


示例18: webgui

def webgui(args):
    os.environ["FWDB_CONFIG"] = json.dumps(get_lp(args).to_dict())
    from fireworks.flask_site.app import app
    if args.wflowquery:
        app.BASE_Q_WF = json.loads(args.wflowquery)
    if args.fwquery:
        app.BASE_Q = json.loads(args.fwquery)
        if "state" in app.BASE_Q:
            app.BASE_Q_WF["state"] = app.BASE_Q["state"]

    if not args.server_mode:
        from multiprocessing import Process
        p1 = Process(
            target=app.run,
            kwargs={"host": args.host, "port": args.port, "debug": args.debug})
        p1.start()
        import webbrowser
        time.sleep(2)
        webbrowser.open("http://{}:{}".format(args.host, args.port))
        p1.join()
    else:
        from fireworks.flask_site.app import bootstrap_app
        try:
            from fireworks.flask_site.gunicorn import (
                StandaloneApplication, number_of_workers)
        except ImportError:
            import sys
            sys.exit("Gunicorn is required for server mode. "
                     "Install using `pip install gunicorn`.")
        options = {
            'bind': '%s:%s' % (args.host, args.port),
            'workers': number_of_workers(),
        }
        StandaloneApplication(bootstrap_app, options).run()
开发者ID:aykol,项目名称:fireworks,代码行数:34,代码来源:lpad_run.py


示例19: authenticate

def authenticate():
    """Authenticate with facebook so you can make api calls that require auth.

    Alternatively you can just set the ACCESS_TOKEN global variable in this
    module to set an access token you get from facebook.

    If you want to request certain permissions, set the AUTH_SCOPE global
    variable to the list of permissions you want.
    """
    global ACCESS_TOKEN
    needs_auth = True
    if os.path.exists(ACCESS_TOKEN_FILE):
        data = json.loads(open(ACCESS_TOKEN_FILE).read())
        expires_at = data.get('expires_at')
        still_valid = expires_at and (expires_at == 'never' or expires_at > time.time())
        if still_valid and set(data['scope']).issuperset(AUTH_SCOPE):
            ACCESS_TOKEN = data['access_token']
            needs_auth = False

    if needs_auth:
        webbrowser.open('https://www.facebook.com/dialog/oauth?' +
                        urlencode({'client_id':APP_ID,
                                   'redirect_uri':'http://127.0.0.1:%s/' % SERVER_PORT,
                                   'response_type':'token',
                                   'scope':','.join(AUTH_SCOPE)}))

        httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', SERVER_PORT), _RequestHandler)
        while ACCESS_TOKEN is None:
            httpd.handle_request()
开发者ID:dhirajt,项目名称:fbconsole,代码行数:29,代码来源:fbconsole.py


示例20: song

def song(karaoke=False):
    """
    Listen to the Gammapy song.

    Make sure you listen on good headphones or speakers. You'll be not disappointed!

    Parameters
    ----------
    karaoke : bool
        Print lyrics to sing along.
    """
    import webbrowser
    import sys

    webbrowser.open("https://gammapy.org/gammapy_song.mp3")

    if karaoke:
        lyrics = (
            "\nGammapy Song Lyrics\n"
            "-------------------\n\n"
            "Gammapy, gamma-ray data analysis package\n"
            "Gammapy, prototype software CTA science tools\n\n"
            "Supernova remnants, pulsar winds, AGN, Gamma, Gamma, Gammapy\n"
            "Galactic plane survey, pevatrons, Gammapy, Gamma, Gammapy\n"
            "Gammapy, github, continuous integration, readthedocs, travis, "
            "open source project\n\n"
            "Gammapy, Gammapy\n\n"
            "Supernova remnants, pulsar winds, AGN, Gamma, Gamma, Gammapy\n"
        )

        centered = "\n".join("{:^80}".format(s) for s in lyrics.split("\n"))
        sys.stdout.write(centered)
开发者ID:adonath,项目名称:gammapy,代码行数:32,代码来源:__init__.py



注:本文中的webbrowser.open函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python webbrowser.open_new函数代码示例发布时间:2022-05-26
下一篇:
Python webbrowser.get函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap