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 |
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 |
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 |
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: login.py From floyd-cli with Apache License 2.0 | 6 votes |
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 #5
Source File: util.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
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 #6
Source File: util.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
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 #7
Source File: misctools.py From svgpathtools with MIT License | 6 votes |
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 #8
Source File: openmct.py From AIT-Core with MIT License | 6 votes |
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 #9
Source File: search.py From socli with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #10
Source File: __init__.py From Blender-Metaverse-Addon with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: pushpin.py From recon-ng-marketplace with GNU General Public License v3.0 | 6 votes |
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 #12
Source File: views.py From dtale with GNU Lesser General Public License v2.1 | 6 votes |
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 #13
Source File: views.py From dtale with GNU Lesser General Public License v2.1 | 6 votes |
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 #14
Source File: views.py From dtale with GNU Lesser General Public License v2.1 | 6 votes |
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 #15
Source File: guy.py From guy with Apache License 2.0 | 6 votes |
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 #16
Source File: wuy.py From wuy with GNU General Public License v2.0 | 5 votes |
def get(self, k: str = None): return self.__d.get(k, None) if k else self.__d
Example #17
Source File: wuy.py From wuy with GNU General Public License v2.0 | 5 votes |
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 #18
Source File: wuy.py From wuy with GNU General Public License v2.0 | 5 votes |
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 #19
Source File: wuy.py From wuy with GNU General Public License v2.0 | 5 votes |
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 #20
Source File: wuy.py From wuy with GNU General Public License v2.0 | 5 votes |
def get(self, key=None, file="config.json"): c = JDict(file) return c.get(key)
Example #21
Source File: login.py From floyd-cli with Apache License 2.0 | 5 votes |
def wait_for_apikey(): floyd_logger.info('Waiting for login from browser...') key_queue = Queue() (hostname, port) = get_free_port() if not port: floyd_logger.error("Failed to allocate TCP port for automatic login.") return server = LoginServer((hostname, port), LoginHttpRequestHandler, key_queue) t = threading.Thread( target=server.serve_forever) t.daemon = True t.start() cli_host = 'http://' + hostname url = '%s/cli_login?fallback=redirect&callback=%s:%s' % (floyd.floyd_web_host, cli_host, port) subprocess.check_output( [sys.executable, '-m', 'webbrowser', url], stderr=subprocess.STDOUT) wait_timeout_sec = 0.5 wait_cnt = 0 while True: if wait_cnt > 60: floyd_logger.error("Failed to get login info from browser, please login manually by creating login key at %s/settings/apikey.", floyd.floyd_web_host) server.shutdown() sys.exit(1) try: apikey = key_queue.get(timeout=wait_timeout_sec) break except QueueEmpty: wait_cnt += 1 server.shutdown() return apikey
Example #22
Source File: login.py From floyd-cli with Apache License 2.0 | 5 votes |
def has_browser(): try: webbrowser.get() return True except webbrowser.Error: return False
Example #23
Source File: util.py From SalesforceXyTools with Apache License 2.0 | 5 votes |
def refresh_token(sf_basic_config): settings = sf_basic_config.get_setting() sublconsole = SublConsole(sf_basic_config) sublconsole.debug('>>>>start to refresh token') from SalesforceXyTools.libs import auth if not settings["use_oauth2"]: return False project_setting = settings is_sandbox = project_setting["is_sandbox"] if "refresh_token" not in project_setting: sublconsole.debug("refresh token missing") return False sublconsole.debug('>>>>load server info') 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) _refresh_token = project_setting["refresh_token"] # sublconsole.debug(refresh_token) response_json = oauth.refresh_token(_refresh_token) # sublconsole.debug(response_json) if "error" in response_json: sublconsole.debug('>>>>response josn error') sublconsole.debug(response_json) return False if "refresh_token" not in response_json: response_json["refresh_token"] = _refresh_token sublconsole.debug('>>>>refresh_token:') sublconsole.debug(refresh_token) sublconsole.debug('>>>>save session') sf_basic_config.save_session(response_json) sublconsole.debug("------->refresh_token ok!") return True
Example #24
Source File: oauth.py From recon-ng with GNU General Public License v3.0 | 5 votes |
def get_explicit_oauth_token(self, resource, scope, authorize_url, access_url): token_name = resource+'_token' token = self.get_key(token_name) if token: return token client_id = self.get_key(resource+'_api') client_secret = self.get_key(resource+'_secret') port = 31337 redirect_uri = f"http://localhost:{port}" payload = {'response_type': 'code', 'client_id': client_id, 'scope': scope, 'state': self.get_random_str(40), 'redirect_uri': redirect_uri} authorize_url = f"{authorize_url}?{urllib.parse.urlencode(payload)}" w = webbrowser.get() w.open(authorize_url) # open a socket to receive the access token callback sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('127.0.0.1', port)) sock.listen(1) conn, addr = sock.accept() data = conn.recv(1024) conn.sendall('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html><head><title>Recon-ng</title></head><body>Response received. Return to Recon-ng.</body></html>') conn.close() # process the received data if 'error_description' in data: self.error(urllib.parse.unquote_plus(re.search(r'error_description=([^\s&]*)', data).group(1))) return None authorization_code = re.search(r'code=([^\s&]*)', data).group(1) payload = {'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': redirect_uri, 'client_id': client_id, 'client_secret': client_secret} resp = self.request('POST', access_url, data=payload) if 'error' in resp.json(): self.error(resp.json()['error_description']) return None access_token = resp.json()['access_token'] self.add_key(token_name, access_token) return access_token
Example #25
Source File: WebBrowser.py From phpsploit with GNU General Public License v3.0 | 5 votes |
def __new__(cls, name): # a boring Mas OS/X case .. blacklist = ['macosx'] lst = [x for x in webbrowser._browsers.keys() if x not in blacklist] lst.append("disabled") lst_repr = repr(lst)[1:-1] if len(lst) < 2 or name == "disabled": if name not in lst + ["", "default"]: raise ValueError("Can't bind to «%s». Valid choices: %s" % (name, lst_repr)) return str.__new__(cls, "disabled") try: if name.lower() in ["", "default"]: name = webbrowser.get().name else: webbrowser.get(name) # another boring Mac OS/X case .. except AttributeError: return str.__new__(cls, "default") except: raise ValueError("Can't bind to «%s». Valid choices: %s" % (name, lst_repr)) return str.__new__(cls, name)
Example #26
Source File: WebBrowser.py From phpsploit with GNU General Public License v3.0 | 5 votes |
def open(self, url): val = self._raw_value() if val == "disabled": print("[-] BROWSER is disabled, open the following URL manually:") print("[-] %s" % url) else: browser = webbrowser.get(self._raw_value()) # try to open url in new browser tab return browser.open_new_tab(url)
Example #27
Source File: _localhost_open_browser.py From webviz-config with MIT License | 5 votes |
def _app_ready(self) -> bool: """Check if the flask instance is ready. """ no_proxy_env = os.environ.get("NO_PROXY") os.environ["NO_PROXY"] = "localhost" try: urllib.request.urlopen(self._url(https=False)) # nosec app_ready = True except urllib.error.URLError: # type: ignore[attr-defined] # The flask instance has not started app_ready = False except ConnectionResetError: # The flask instance has started but (correctly) abort # request due to "401 Unauthorized" app_ready = True finally: os.environ["NO_PROXY"] = no_proxy_env if no_proxy_env else "" return app_ready
Example #28
Source File: _user_preferences.py From webviz-config with MIT License | 5 votes |
def set_user_preferences( theme: Optional[str] = None, browser: Optional[str] = None ) -> None: preferences = ( json.loads(USER_SETTINGS_FILE.read_text()) if USER_SETTINGS_FILE.is_file() else {} ) new_preferences = {} if theme is not None: if theme not in installed_themes: raise ValueError( f"Theme {theme} is not one of the installed themes ({', '.join(installed_themes)})" ) new_preferences["theme"] = theme if browser is not None: try: webbrowser.get(using=browser) except webbrowser.Error: raise ValueError( f"Could not find an installed browser with the name {browser}." ) new_preferences["browser"] = browser if new_preferences: preferences.update(new_preferences) os.makedirs(USER_SETTINGS_FILE.parent, exist_ok=True) USER_SETTINGS_FILE.write_text(json.dumps(preferences))
Example #29
Source File: _user_preferences.py From webviz-config with MIT License | 5 votes |
def get_user_preference(setting: str) -> Optional[str]: return ( json.loads(USER_SETTINGS_FILE.read_text()).get(setting) if USER_SETTINGS_FILE.is_file() else None )
Example #30
Source File: main.py From WxConn with MIT License | 5 votes |
def processIncoming(self): """Handle all messages currently in the queue, if any.""" while self.queue.qsize(): print "processIncoming" try: msg = self.queue.get(0) print msg if msg['mode'] == WHAT_GOT_QR: self.qrscan.update_qrcode() elif msg['mode'] == WHAT_NOTIFY_CONFIRM: self.qrscan.update_to_confirm() elif msg['mode'] == WHAT_LOGIN_SUCCESS: self.gotoMain() elif msg['mode'] == WHAT_UPDATE_PROGRESS: progress = msg['progress'] self.main.update_progress(value=progress) elif msg['mode'] == WHAT_DONE: self.main.done() elif msg['mode'] == WHAT_ANALYSIS_DATA: self.main.update_generating() self.generate_sex_pic(msg['sex_data']) self.generate_city_pic(msg['city_data']) self.generate_province_pic(msg['provinces_data']) self.generator.start() elif msg['mode'] == WHAT_PRE_LOGIN_SUCCESS: self.qrscan.update_to_pre_login_success() #ALS.generate_result(com_queue=self.queue) # Check contents of message and do whatever is needed. As a # simple test, print it (in real life, you would # suitably update the GUI's display in a richer fashion). except Queue.Empty: # just on general principles, although we don't # expect this branch to be taken in this case pass