Python webbrowser.get() Examples

The following are 30 code examples of webbrowser.get(). 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: 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 #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: _localhost_open_browser.py    From webviz-config with MIT License 7 votes vote down vote up
def _get_browser_controller() -> webbrowser.BaseBrowser:

        if get_user_preference("browser") is not None:
            try:
                return webbrowser.get(using=get_user_preference("browser"))
            except webbrowser.Error:
                warnings.warn("Could not find the user preferred browser.")

        for browser in ["chrome", "chromium-browser"]:
            try:
                return webbrowser.get(using=browser)
            except webbrowser.Error:
                pass

        # Return default browser if none of the
        # preferred browsers are installed:
        return webbrowser.get() 
Example #4
Source File: guy.py    From guy with Apache License 2.0 6 votes vote down vote up
def open(self,id):
        o=Guy._instances.get( id )
        if o:
            logger.debug("Connect %s",id)

            async def doInit( instance ):
                init=instance._getRoutage("init")
                if init:
                    if asyncio.iscoroutinefunction( init ):
                        await instance(self,"init")
                    else:
                        instance(self,"init")

            asyncio.ensure_future( doInit(o) )

            WebSocketHandler.clients[self]=o 
Example #5
Source File: login.py    From floyd-cli with Apache License 2.0 6 votes vote down vote up
def do_GET(self):
        params = urlparse.parse_qs(urlparse.urlparse(self.path).query)
        key = params.get('apikey')
        if not key:
            self.send_response(400)
            return

        self.server.key_queue.put(key[0])

        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
        self.send_header('Content-type', 'text/html')
        self.end_headers()

        page_content = ("""
            <html>
            <header>
             <script>
               window.location.replace("%s/cli_login?keystate=sent");
             </script>
            </header>
            </html>
        """ % (floyd.floyd_web_host)).encode('utf-8')
        self.wfile.write(page_content) 
Example #6
Source File: util.py    From SalesforceXyTools with Apache License 2.0 6 votes vote down vote up
def sf_oauth2(sf_basic_config):
    sublconsole = SublConsole(sf_basic_config)
    settings =  sf_basic_config.get_setting()
    from SalesforceXyTools.libs import auth
    project_setting = settings
    # project_setting = settings["default_project_value"]
    is_sandbox = project_setting["is_sandbox"]

    if refresh_token(sf_basic_config):
        return

    server_info = sublime.load_settings("sfdc.server.sublime-settings")
    client_id = server_info.get("client_id")
    client_secret = server_info.get("client_secret")
    redirect_uri = server_info.get("redirect_uri")
    oauth = auth.SalesforceOAuth2(client_id, client_secret, redirect_uri, is_sandbox)
    authorize_url = oauth.authorize_url()
    sublconsole.debug('authorize_url-->')
    sublconsole.debug(authorize_url)
    start_server()
    open_in_default_browser(sf_basic_config, authorize_url) 
Example #7
Source File: __init__.py    From Blender-Metaverse-Addon with GNU General Public License v3.0 6 votes vote down vote up
def execute(self, context):
        user_preferences = context.preferences
        addon_prefs = user_preferences.addons[metaverse_tools.__name__].preferences

        if not "gateway_server" in addon_prefs.keys():
            addon_prefs["gateway_server"] = default_gateway_server

        server = addon_prefs["gateway_server"]

        browsers = webbrowser._browsers
        # Better way would be to use jwt, but this is just a proto
        routes = GatewayClient.routes(server)
        # TODO On failure this should return something else.

        path = routes["uploads"] + "?" + urlencode({'token': addon_prefs["gateway_token"],
                                                    'username': addon_prefs["gateway_username"]})
        if "windows-default" in browsers:
            print("Windows detected")
            webbrowser.get("windows-default").open(server + path)
        else:
            webbrowser.open(server + path)

        return {'FINISHED'}

# ----- 
Example #8
Source File: util.py    From SalesforceXyTools with Apache License 2.0 6 votes vote down vote up
def reload(self):
        self.sublconsole.showlog("start to reload metadata cache, please wait...")
        self.clean()
        allMetadataResult = self.meta_api.describe()
        
        allMetadataMap = {}
        allMetadataMap["sobjects"] = {}
        for meta in allMetadataResult["sobjects"]:
            name = meta["name"]
            allMetadataMap["sobjects"][name] = meta
        allMetadataMap["lastUpdated"] = str(datetime.now())
        self.save_dict(allMetadataMap)
        self.sublconsole.showlog("load metadata cache done.")
        # self.sublconsole.save_and_open_in_panel(json.dumps(allMetadataMap, ensure_ascii=False, indent=4), self.save_dir, self.file_name , is_open=False)

    # get all fields from sobject 
Example #9
Source File: misctools.py    From svgpathtools with MIT License 6 votes vote down vote up
def open_in_browser(file_location):
    """Attempt to open file located at file_location in the default web
    browser."""

    # If just the name of the file was given, check if it's in the Current
    # Working Directory.
    if not os.path.isfile(file_location):
        file_location = os.path.join(os.getcwd(), file_location)
    if not os.path.isfile(file_location):
        raise IOError("\n\nFile not found.")

    #  For some reason OSX requires this adjustment (tested on 10.10.4)
    if sys.platform == "darwin":
        file_location = "file:///"+file_location

    new = 2  # open in a new tab, if possible
    webbrowser.get().open(file_location, new=new) 
Example #10
Source File: openmct.py    From AIT-Core with MIT License 6 votes vote down vote up
def start_browser(self, url, name=None):
        browser = None

        if name is not None and name.lower() == 'none':
            log.info('Will not start any browser since --browser=none')
            return

        try:
            browser = webbrowser.get(name)
        except webbrowser.Error:
            old     = name or 'default'
            msg     = 'Could not find browser: %s.  Will use: %s.'
            browser = webbrowser.get()
            log.warn(msg, name, self.getBrowserName(browser))

        if type(browser) is webbrowser.GenericBrowser:
            msg = 'Will not start text-based browser: %s.'
            log.info(msg % self.getBrowserName(browser))
        elif browser is not None:
            log.info('Starting browser: %s' % self.getBrowserName(browser))
            browser.open_new(url) 
Example #11
Source File: search.py    From socli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_question_stats_and_answer(url):
    """
    Fetch the content of a StackOverflow page for a particular question.
    :param url: full url of a StackOverflow question
    :return: tuple of ( question_title, question_desc, question_stats, answers )
    """
    random_headers()
    res_page = requests.get(url, headers=header)
    captcha_check(res_page.url)
    soup = BeautifulSoup(res_page.text, 'html.parser')
    question_title, question_desc, question_stats = get_stats(soup)
    answers = [s.get_text() for s in soup.find_all("div", class_="post-text")][
              1:]  # first post is question, discard it.
    if len(answers) == 0:
        answers.append('No answers for this question ...')
    return question_title, question_desc, question_stats, answers 
Example #12
Source File: pushpin.py    From recon-ng-marketplace with GNU General Public License v3.0 6 votes vote down vote up
def module_run(self):
        key = self.keys.get('google_api')
        sources = self.query('SELECT COUNT(source), source FROM pushpins GROUP BY source')
        media_content, map_content = self.build_content(sources)
        meta_content = (self.options['latitude'], self.options['longitude'], self.options['radius'])
        # create the media report
        media_content = meta_content + media_content
        media_filename = self.options['media_filename']
        self.write_markup(os.path.join(self.data_path, 'template_media.html'), media_filename, media_content)
        self.output(f"Media data written to '{media_filename}'")
        # order the map_content tuple
        map_content = meta_content + map_content + (key,)
        order = [6, 4, 0, 1, 2, 3, 5]
        map_content = tuple([map_content[i] for i in order])
        # create the map report
        map_filename = self.options['map_filename']
        self.write_markup(os.path.join(self.data_path, 'template_map.html'), map_filename, map_content)
        self.output(f"Mapping data written to '{map_filename}'")
        # open the reports in a browser
        w = webbrowser.get()
        w.open(media_filename)
        time.sleep(2)
        w.open(map_filename) 
Example #13
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 6 votes vote down vote up
def delete_col(data_id, column):
    data = global_state.get_data(data_id)
    data = data[[c for c in data.columns if c != column]]
    curr_history = global_state.get_history(data_id) or []
    curr_history += ['df = df[[c for c in df.columns if c != "{}"]]'.format(column)]
    global_state.set_history(data_id, curr_history)
    dtypes = global_state.get_dtypes(data_id)
    dtypes = [dt for dt in dtypes if dt["name"] != column]
    curr_settings = global_state.get_settings(data_id)
    curr_settings["locked"] = [
        c for c in curr_settings.get("locked", []) if c != column
    ]
    global_state.set_data(data_id, data)
    global_state.set_dtypes(data_id, dtypes)
    global_state.set_settings(data_id, curr_settings)
    return jsonify(success=True) 
Example #14
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 6 votes vote down vote up
def rename_col(data_id, column):
    rename = get_str_arg(request, "rename")
    data = global_state.get_data(data_id)
    if column != rename and rename in data.columns:
        return jsonify(error='Column name "{}" already exists!')

    data = data.rename(columns={column: rename})
    curr_history = global_state.get_history(data_id) or []
    curr_history += ["df = df.rename(columns={'%s': '%s'})" % (column, rename)]
    global_state.set_history(data_id, curr_history)
    dtypes = global_state.get_dtypes(data_id)
    dtypes = [
        dict_merge(dt, {"name": rename}) if dt["name"] == column else dt
        for dt in dtypes
    ]
    curr_settings = global_state.get_settings(data_id)
    curr_settings["locked"] = [
        rename if c == column else c for c in curr_settings.get("locked", [])
    ]
    global_state.set_data(data_id, data)
    global_state.set_dtypes(data_id, dtypes)
    global_state.set_settings(data_id, curr_settings)
    return jsonify(success=True) 
Example #15
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 6 votes vote down vote up
def data_export(data_id):
    curr_settings = global_state.get_settings(data_id) or {}
    curr_dtypes = global_state.get_dtypes(data_id) or []
    data = run_query(
        global_state.get_data(data_id),
        build_query(data_id, curr_settings.get("query")),
        global_state.get_context_variables(data_id),
        ignore_empty=True,
    )
    data = data[
        [
            c["name"]
            for c in sorted(curr_dtypes, key=lambda c: c["index"])
            if c["visible"]
        ]
    ]
    tsv = get_str_arg(request, "tsv") == "true"
    file_ext = "tsv" if tsv else "csv"
    csv_buffer = export_to_csv_buffer(data, tsv=tsv)
    filename = build_chart_filename("data", ext=file_ext)
    return send_file(csv_buffer.getvalue(), filename, "text/{}".format(file_ext)) 
Example #16
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def update_formats(data_id):
    """
    :class:`flask:flask.Flask` route which updates the "formats" property for global SETTINGS associated w/ the
    current port

    :param data_id: integer string identifier for a D-Tale process's data
    :type data_id: str
    :param all: boolean flag which, if true, tells us we should apply this formatting to all columns with the same
                data type as our selected column
    :param col: selected column
    :param format: JSON string for the formatting configuration we want applied to either the selected column of all
                   columns with the selected column's data type
    :return: JSON
    """
    update_all_dtype = get_bool_arg(request, "all")
    col = get_str_arg(request, "col")
    col_format = get_json_arg(request, "format")
    curr_settings = global_state.get_settings(data_id) or {}
    updated_formats = {col: col_format}
    if update_all_dtype:
        dtypes = global_state.get_dtypes(data_id)
        col_dtype = next((c["dtype"] for c in dtypes if c["name"] == col), None)
        updated_formats = {
            c["name"]: col_format
            for c in global_state.get_dtypes(data_id)
            if c["dtype"] == col_dtype
        }
    updated_formats = dict_merge(curr_settings.get("formats") or {}, updated_formats)
    updated_settings = dict_merge(curr_settings, dict(formats=updated_formats))
    global_state.set_settings(data_id, updated_settings)
    return jsonify(dict(success=True)) 
Example #17
Source File: wuy.py    From wuy with GNU General Public License v2.0 5 votes vote down vote up
def handleProxy(req):  # proxify "/_/<url>" with headers starting with "set-"
    url = req.match_info.get("url", None)
    if req.query_string:
        url = url + "?" + req.query_string
    headers = {k[4:]: v for k, v in req.headers.items() if k.lower().startswith("set-")}
    r = await request(
        url, data=req.can_read_body and (await req.text()), headers=headers
    )
    wlog(". serve proxy url", url, headers, ":", r.status)
    h = {"Server": "Wuy Proxified request (%s)" % __version__}
    for k, v in r.headers.items():
        if k.lower() in ["content-type", "date", "expires", "cache-control"]:
            h[k] = v
    return web.Response(status=r.status or 0, text=r.content, headers=h) 
Example #18
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def _view_main(data_id, iframe=False):
    """
    Helper function rendering main HTML which will also build title and store whether we are viewing from an <iframe>

    :param data_id: integer string identifier for a D-Tale process's data
    :type data_id: str
    :param iframe: boolean flag indicating whether this is being viewed from an <iframe> (usually means ipython)
    :type iframe: bool, optional
    :return: HTML
    """
    curr_metadata = global_state.get_metadata(data_id) or {}
    title = "D-Tale"
    if curr_metadata.get("name"):
        title = "{} ({})".format(title, curr_metadata["name"])
    return base_render_template("dtale/main.html", data_id, title=title, iframe=iframe) 
Example #19
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def open_browser(self):
        """
        This function uses the :mod:`python:webbrowser` library to try and automatically open server's default browser
        to this D-Tale instance
        """
        webbrowser.get().open(self._main_url) 
Example #20
Source File: wuy.py    From wuy with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, url, size=None, chromeArgs=[]):
        self.__instance = None

        if sys.platform[:3] == "win":
            exe = find_chrome_win()
        elif sys.platform == "darwin":
            exe = find_chrome_mac()
        else:
            for i in ["chromium-browser", "chromium", "google-chrome", "chrome"]:
                try:
                    exe = webbrowser.get(i).name
                    break
                except webbrowser.Error:
                    exe = None

        if exe:
            args = [exe, "--app=" + url] + chromeArgs
            if size == FULLSCREEN:
                args.append("--start-fullscreen")
            if tempfile.gettempdir():
                args.append(
                    "--user-data-dir=%s"
                    % os.path.join(tempfile.gettempdir(), ".wuyapp")
                )
            # self.__instance = subprocess.Popen( args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) # make troubles on windows (freezd with noconsole don't start)
            self.__instance = subprocess.Popen(args)
        else:
            raise Exception("no browser") 
Example #21
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def update_visibility(data_id):
    """
    :class:`flask:flask.Flask` route to handle saving state associated visiblity of columns on the front-end

    :param data_id: integer string identifier for a D-Tale process's data
    :type data_id: str
    :param visibility: string from flask.request.args['action'] of dictionary of visibility of all columns in a
                       dataframe
    :type visibility: dict, optional
    :param toggle: string from flask.request.args['col'] of column name whose visibility should be toggled
    :type toggle: str, optional
    :return: JSON {success: True/False}
    """
    curr_dtypes = global_state.get_dtypes(data_id)
    if request.form.get("visibility"):
        visibility = json.loads(request.form.get("visibility", "{}"))
        global_state.set_dtypes(
            data_id,
            [dict_merge(d, dict(visible=visibility[d["name"]])) for d in curr_dtypes],
        )
    elif request.form.get("toggle"):
        toggle_col = request.form.get("toggle")
        toggle_idx = next(
            (idx for idx, d in enumerate(curr_dtypes) if d["name"] == toggle_col), None
        )
        toggle_cfg = curr_dtypes[toggle_idx]
        curr_dtypes[toggle_idx] = dict_merge(
            toggle_cfg, dict(visible=not toggle_cfg["visible"])
        )
        global_state.set_dtypes(data_id, curr_dtypes)
    return jsonify(success=True) 
Example #22
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def view_popup(popup_type, data_id=None):
    """
    :class:`flask:flask.Flask` route which serves up a base jinja template for any popup, additionally forwards any
    request parameters as input to template.

    :param popup_type: type of popup to be opened. Possible values: charts, correlations, describe, histogram, instances
    :type popup_type: str
    :param data_id: integer string identifier for a D-Tale process's data
    :type data_id: str
    :return: HTML
    """
    if data_id is None:
        return redirect("/dtale/popup/{}/{}".format(popup_type, head_data_id()))
    curr_metadata = global_state.get_metadata(data_id) or {}
    title = "D-Tale"
    if curr_metadata.get("name"):
        title = "{} ({})".format(title, curr_metadata["name"])
    if popup_type == "reshape":
        popup_title = "Summarize Data"
    elif popup_type == "filter":
        popup_title = "Custom Filter"
    else:
        popup_title = " ".join([pt.capitalize() for pt in popup_type.split("-")])
    title = "{} - {}".format(title, popup_title)
    params = request.args.to_dict()
    if len(params):

        def pretty_print(obj):
            return ", ".join(["{}: {}".format(k, str(v)) for k, v in obj.items()])

        title = "{} ({})".format(title, pretty_print(params))
    return base_render_template(
        "dtale/popup.html",
        data_id,
        title=title,
        popup_title=popup_title,
        js_prefix=popup_type,
    ) 
Example #23
Source File: wuy.py    From wuy with GNU General Public License v2.0 5 votes vote down vote up
def request(
    url, data=None, headers={}
):  # mimic urllib.Request() (GET & POST only)
    async with aiohttp.ClientSession(cookie_jar=jar) as session:
        try:
            if data:
                async with session.post(
                    url, data=data, headers=headers, ssl=False
                ) as resp:
                    return Response(
                        resp.status, await resp.text(), headers=resp.headers
                    )
            else:
                async with session.get(url, headers=headers, ssl=False) as resp:
                    return Response(
                        resp.status, await resp.text(), headers=resp.headers
                    )
        except aiohttp.client_exceptions.ClientConnectorError as e:
            return Response(None, str(e))


# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


# Async aiohttp things (use current)
############################################################# 
Example #24
Source File: utils.py    From anvio with GNU General Public License v3.0 5 votes vote down vote up
def get_ordinal_from_integer(num):
    """append 'st', 'nd', or 'th' to integer to make categorical. num must be integer"""
    return'%d%s' % (num, {11:'th', 12:'th', 13:'th'}.get(num%100, {1:'st', 2:'nd', 3:'rd'}.get(num%10,'th'))) 
Example #25
Source File: utils.py    From anvio with GNU General Public License v3.0 5 votes vote down vote up
def get_constant_value_blocks(array, value):
    """Generator that returns blocks of consecutive numbers

    Parameters
    ==========
    array : array
        a numerical numpy array. If a list is passed, this function is very slow

    value : number
        The number you want to get constant blocks for.

    Examples
    ========

    >>> a = np.array([47, 47, 47, 49, 50, 47, 47, 99])
    >>> for i in get_constant_value_blocks(a, 47): print(i)
    (0, 3)
    (5, 7)
    """
    ans = []

    matching = False
    for i in range(len(array)):
        if array[i] == value:
            if not matching:
                start = i
                matching = True
        else:
            if matching:
                matching = False
                ans.append((start, i))

    if matching:
        ans.append((start, i + 1))

    return ans 
Example #26
Source File: utils.py    From anvio with GNU General Public License v3.0 5 votes vote down vote up
def get_required_version_for_db(db_path):
    db_type = get_db_type(db_path)

    if db_type not in t.versions_for_db_types:
        raise ConfigError("Anvi'o was trying to get the version of the -alleged- anvi'o database '%s', but it failed "
                           "because it turns out it doesn't know anything about this '%s' type." % (db_path, db_type))

    return t.versions_for_db_types[db_type] 
Example #27
Source File: utils.py    From anvio with GNU General Public License v3.0 5 votes vote down vote up
def get_all_item_names_from_the_database(db_path, run=run):
    """Return all split names or gene cluster names in a given database"""

    all_items = set([])

    database = db.DB(db_path, get_required_version_for_db(db_path))
    db_type = database.get_meta_value('db_type')

    if db_type == 'profile':
        if is_blank_profile(db_path):
            run.warning("Someone asked for the split names in a blank profile database. Sadly, anvi'o does not keep track "
                        "of split names in blank profile databases. This function will return an empty set as split names "
                        "to not kill your mojo, but whatever you were trying to do will not work :(")
            return set([])
        elif int(database.get_meta_value('merged')):
            all_items = set(database.get_single_column_from_table('mean_coverage_Q2Q3_splits', 'contig'))
        else:
            all_items = set(database.get_single_column_from_table('atomic_data_splits', 'contig'))
    elif db_type == 'pan':
        all_items = set(database.get_single_column_from_table(t.pan_gene_clusters_table_name, 'gene_cluster_id'))
    elif db_type == 'contigs':
        all_items = set(database.get_single_column_from_table(t.splits_info_table_name, 'split'))
    elif db_type == 'genes':
        all_items = set([str(i) for i in database.get_single_column_from_table(t.gene_level_coverage_stats_table_name, 'gene_callers_id')])
    else:
        database.disconnect()
        raise ConfigError("You wanted to get all items in the database %s, but no one here knows about its type. Seriously,\
                            what is '%s' anyway?" % (db_path, db_type))

    if not len(all_items):
        database.disconnect()
        raise ConfigError("utils::get_all_item_names_from_the_database speaking. Something that should never happen happened :/ "
                          "There seems to be nothing in this %s database. Anvi'o is as confused as you are. Please get in touch "
                          "with a developer. They will love this story." % db_path)

    database.disconnect()

    return all_items 
Example #28
Source File: utils.py    From anvio with GNU General Public License v3.0 5 votes vote down vote up
def open_url_in_browser(url, browser_path=None, run=run):
    if browser_path:
        filesnpaths.is_file_exists(browser_path)
        run.info_single('You are launching an alternative browser. Keep an eye on things!', mc='red', nl_before=1)
        webbrowser.register('users_preferred_browser', None, webbrowser.BackgroundBrowser(browser_path))
        webbrowser.get('users_preferred_browser').open_new(url)
    else:
        webbrowser.open_new(url) 
Example #29
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, data_id, url):
        self._data_id = data_id
        self._url = url
        self._name_or_data_id = global_state.convert_name_to_url_path(
            (global_state.get_metadata(self._data_id) or {}).get("name")
        )
        if self._name_or_data_id is None:
            self._name_or_data_id = self._data_id
        self._main_url = self.build_main_url()
        self._notebook_handle = None 
Example #30
Source File: stravaio.py    From stravaio with MIT License 5 votes vote down vote up
def __init__(self, api_response):
        """
        Parameters
        ----------
        api_response: swagger_client.get...() object
            e.g. athletes_api.get_logged_in_athlete()
        """
        self.api_response = api_response
        self.id = self.api_response.id