我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用webbrowser.get()。
def show_in_panel(cls, panel_name, message_str): panel = cls.panels.get(panel_name) window = sublime.active_window() if not panel: panel = window.get_output_panel(panel_name) panel.settings().set('syntax', 'Packages/Java/Java.tmLanguage') panel.settings().set('color_scheme', 'Packages/Color Scheme - Default/Monokai.tmTheme') panel.settings().set('word_wrap', True) panel.settings().set('gutter', True) panel.settings().set('line_numbers', True) cls.panels[panel_name] = panel window.run_command('show_panel', { 'panel': 'output.' + panel_name }) if message_str: message_str += '\n' panel.run_command("append", { "characters": message_str })
def del_comment(soql): result = soql if soql: # TODO # soql = soql.strip().replace('\t', ' ').replace('\r\n', ' ').replace('\n', ' ') soql = soql.strip().replace('\t', ' ') # delete // comment result1, number = re.subn("//.*", "", soql) # delete /**/ comment result, number = re.subn("/\*([\s|\S]*?)\*/", "", result1, flags=re.M) result = result.strip() # show_in_panel(result) return result # get sobject name from soql
def _delayed_open_web_browser(url, delay, new=0, autoraise=True, specific_browser=None): ''' Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the same time. Insert a small sleep before opening a web-browser this gives Flask a chance to start running before the browser starts requesting data from Flask. ''' def _sleep_and_open_web_browser(url, delay, new, autoraise, specific_browser): sleep(delay) browser = webbrowser # E.g. On OSX the following would use the Chrome browser app from that location # specific_browser = 'open -a /Applications/Google\ Chrome.app %s' if specific_browser: browser = webbrowser.get(specific_browser) browser.open(url, new=new, autoraise=autoraise) thread = Thread(target=_sleep_and_open_web_browser, kwargs=dict(url=url, new=new, autoraise=autoraise, delay=delay, specific_browser=specific_browser)) thread.daemon = True # Force to quit on main quitting thread.start()
def attempt_open(url): import os import webbrowser if 'DISPLAY' not in os.environ: print('The DISPLAY variable is not set, so not attempting to open a web browser\n') return False for name in 'windows-default chrome chromium mozilla firefox opera safari'.split(): # LATER: prepend `macosx` to this list when <http://bugs.python.org/issue30392> is fixed. try: b = webbrowser.get(name) except: pass else: if b.open(url): return True return False
def handleRequest(self, env, start_response): path = env["PATH_INFO"] if env.get("QUERY_STRING"): get = dict(cgi.parse_qsl(env['QUERY_STRING'])) else: get = {} ui_request = UiRequest(self, get, env, start_response) if config.debug: # Let the exception catched by werkezung return ui_request.route(path) else: # Catch and display the error try: return ui_request.route(path) except Exception, err: logging.debug("UiRequest error: %s" % Debug.formatException(err)) return ui_request.error500("Err: %s" % Debug.formatException(err)) # Reload the UiRequest class to prevent restarts in debug mode
def _delayed_open_web_browser(url, delay, new=0, autoraise=True, specific_browser=None): """ Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the same time. Insert a small sleep before opening a web-browser this gives Flask a chance to start running before the browser starts requesting data from Flask. """ def _sleep_and_open_web_browser(url, delay, new, autoraise, specific_browser): sleep(delay) browser = webbrowser # E.g. On OSX the following would use the Chrome browser app from that location # specific_browser = 'open -a /Applications/Google\ Chrome.app %s' if specific_browser: browser = webbrowser.get(specific_browser) browser.open(url, new=new, autoraise=autoraise) thread = Thread(target=_sleep_and_open_web_browser, kwargs=dict(url=url, new=new, autoraise=autoraise, delay=delay, specific_browser=specific_browser)) thread.daemon = True # Force to quit on main quitting thread.start()
def generateNewTorrentAPIToken(error=False): global auth_token headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} refresh_url = 'https://torrentapi.org/pubapi_v2.php?get_token=get_token' try: auth_token = json.loads(requests.get(refresh_url, headers=headers).text)['token'].encode('utf-8') if error != False: success_string = '[RARBG] Success : Generated new token! ' print colored.blue(success_string) except requests.exceptions.ConnectionError, e: err_string = str(e).split(',')[0] if 'Connection aborted' in err_string: print colored.red("Server cannot be reached. Check Internet connectivity!") sys.exit(1) except SysCallError, e: print colored.red("SysCallError for RARBG search. Fix?")
def searchRarbg(search_string=defaultQuery): global auth_token, results_rarbg, error_detected_rarbg # API Documentaion : https://torrentapi.org/apidocs_v2.txt # https://torrentapi.org/pubapi_v2.php?mode=search&search_string=Suits%20S06E10&format=json_extended&ranked=0&token=cy6xjhtmev generateNewTorrentAPIToken() search_string = search_string.replace(" ", "%20") base_url = 'https://torrentapi.org/pubapi_v2.php?' new_token = 'get_token=get_token' search_criteria = 'mode=search&search_string=' + search_string + "&" options = 'format=json_extended&ranked=0&token=' + auth_token url = base_url + search_criteria + options headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} response = requests.get(url, headers=headers) response_json = json.loads(response.text) #print response_json results_rarbg = [] error_detected_rarbg = checkResponseForErrors(response_json) if(error_detected_rarbg == False): results_rarbg = parse_results_rarbg(response_json) return results_rarbg
def module_run(self): 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('Media data written to \'%s\'' % (media_filename)) # order the map_content tuple map_content = meta_content + map_content order=[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('Mapping data written to \'%s\'' % (map_filename)) # open the reports in a browser w = webbrowser.get() w.open(media_filename) time.sleep(2) w.open(map_filename)
def dispres(url): """ Display result page :param url: URL of the search result :return: """ global question_post global header_for_display global LOOP randomheaders() res_page = requests.get(url, headers=header) captchacheck(res_page.url) header_for_display = Header() question_title, question_desc, question_stats, answers = get_question_stats_and_answer(url) question_post = QuestionPage((answers, question_title, question_desc, question_stats, url)) LOOP = EditedMainLoop(question_post, palette) LOOP.run()
def __init__(self): """Class constructor.""" self._fields_to_check = ['description', 'name', 'summary', 'reviews'] self._minimum_monthly_discount = int(settings.get('MINIMUM_MONTHLY_DISCOUNT', None)) self._minimum_weekly_discount = int(settings.get('MINIMUM_WEEKLY_DISCOUNT', None)) self._skip_list = settings.get('SKIP_LIST', None) self._cannot_have_regex = settings.get('CANNOT_HAVE', None) if self._cannot_have_regex: self._cannot_have_regex = re.compile(str(self._cannot_have_regex), re.IGNORECASE) self._must_have_regex = settings.get('MUST_HAVE', None) if self._must_have_regex: self._must_have_regex = re.compile(str(self._must_have_regex), re.IGNORECASE) self._web_browser = settings.get('WEB_BROWSER', None) if self._web_browser: self._web_browser += ' %s' # append URL placeholder (%s)
def select_and_open (url, cfg): """Select the browser to use via configuration and open the URL""" # set default browser log.debug("Initialise with default browser") selected_browser = webbrowser.get(cfg.browser_default) # set browser according to rules for r in cfg.rules: url_pattern = r.get('url_pattern') url_replace = r.get('url_replace') browser_id = r.get('browser_id') if isinstance(url_pattern, basestring): p = re.compile(url_pattern) if p.search(url): if isinstance(url_replace, basestring): url = p.sub(url_replace, url) if isinstance(browser_id, basestring): log.debug("-- Set browser to browser '%s'" % browser_id) selected_browser = webbrowser.get(browser_id) log.info("Selected browser: '%s %s'" % (selected_browser.name, ' '.join(selected_browser.args))) log.info("URL to open via 'open_new_tab': '%s'" % url) selected_browser.open_new_tab(url) log.debug("'open_new_tab' done")
def sf_oauth2(): from .libs import auth settings = setting.load() default_project_value = settings["default_project_value"] is_sandbox = default_project_value["is_sandbox"] if refresh_token(): 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() print('authorize_url-->') print(authorize_url) start_server() open_in_default_browser(authorize_url)
def _solve_google_captcha(self, resp): # set up the captcha page markup for parsing tree = fromstring(resp.text) # extract and request the captcha image resp = self.request('https://ipv4.google.com' + tree.xpath('//img/@src')[0], redirect=False, cookiejar=self.cookiejar, agent=self.user_agent) # store the captcha image to the file system with tempfile.NamedTemporaryFile(suffix='.jpg') as fp: fp.write(resp.raw) fp.flush() # open the captcha image for viewing in gui environments w = webbrowser.get() w.open('file://' + fp.name) self.alert(fp.name) _payload = {'captcha':raw_input('[CAPTCHA] Answer: ')} # temporary captcha file removed on close # extract the form elements for the capctah answer request form = tree.xpath('//form[@action="CaptchaRedirect"]')[0] for x in ['continue', 'id', 'submit']: _payload[x] = form.xpath('//input[@name="%s"]/@value' % (x))[0] # send the captcha answer return self.request('https://ipv4.google.com/sorry/CaptchaRedirect', payload=_payload, cookiejar=self.cookiejar, agent=self.user_agent)
def browse_website(self, browser=None): """ Launch web browser at project's homepage @param browser: name of web browser to use @type browser: string @returns: 0 if homepage found, 1 if no homepage found """ if len(self.all_versions): metadata = self.pypi.release_data(self.project_name, \ self.all_versions[0]) self.logger.debug("DEBUG: browser: %s" % browser) if metadata.has_key("home_page"): self.logger.info("Launching browser: %s" \ % metadata["home_page"]) if browser == 'konqueror': browser = webbrowser.Konqueror() else: browser = webbrowser.get() browser.open(metadata["home_page"], 2) return 0 self.logger.error("No homepage URL found.") return 1
def _solve_google_captcha(self, resp): # set up the captcha page markup for parsing tree = fromstring(resp.text) # extract and request the captcha image resp = self.request('https://ipv4.google.com' + tree.xpath('//img/@src')[0], redirect=False, cookiejar=self.cookiejar, agent=self.user_agent) # store the captcha image to the file system with tempfile.NamedTemporaryFile(suffix='.jpg') as fp: fp.write(resp.raw) fp.flush() # open the captcha image for viewing in gui environments w = webbrowser.get() w.open('file://' + fp.name) self.alert(fp.name) _payload = {'captcha':raw_input('[CAPTCHA] Answer: ')} # temporary captcha file removed on close # extract the form elements for the capctah answer request form = tree.xpath('//form[@action="index"]')[0] for x in ['q', 'continue', 'submit']: _payload[x] = form.xpath('//input[@name="%s"]/@value' % (x))[0] # send the captcha answer return self.request('https://ipv4.google.com/sorry/index', payload=_payload, cookiejar=self.cookiejar, agent=self.user_agent)
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)
def create_or_reset_admin(context, settings_path=None): ''' Creates an admin user or resets the password for an existing one ''' # Find the path to the settings and setup the django environment setup_django_environment(settings_path) # can't be imported in global scope as it already requires # the settings module during import from wger.manager.models import User try: admin = User.objects.get(username="admin") print("*** Password for user admin was reset to 'admin'") except User.DoesNotExist: print("*** Created default admin user") # os.chdir(os.path.dirname(inspect.stack()[0][1])) # current_dir = os.path.join(os.getcwd(), 'wger') current_dir = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(current_dir, 'wger', 'core', 'fixtures/') call_command("loaddata", path + "users.json")
def callbackEditUnicodeText(self, sender): # this is the callback for the unicode textbox. # if text is edited here, find the glyphs that are used in the text # and add those to the selection. This way we can quickly add characters # from cut / paste text to the selection f = CurrentFont() text = sender.get() text = text.replace("\r", " ") text = text.replace("\n", " ") self._typing = True if text: glyphSelection = findText(self.data, text) glyphSelection.sort() items = [g.asDict(self._unicodes, self._names, self.joiningTypes) for g in glyphSelection] items = sorted(items, key=lambda x: x['uni'], reverse=False) self.w.selectedNames.set(items) self.w.selectionUnicodeText.set(text) self._typing = False self.checkSampleSize()
def demo(base_url): """Login through a third-party OAuth handler and print some stats. Parameters ---------- base_url : str Base URL of the CMS server. """ session = requests.Session() adapter = HTTPAdapter(max_retries=Retry(total=3, backoff_factor=0.02)) session.mount('{}://'.format(urlparse(base_url).scheme), adapter) wb = webbrowser.get() login_url = os.path.join(base_url, "login?complete=no") session.get(login_url) wb.open(login_url) auth_url = input("Enter the URL returned after authentication:") response = session.get(auth_url.replace("complete=no", 'complete=yes')) assert response.status_code == 200 print(session.get(os.path.join(base_url, 'me')).content)
def _github_connect(self, msg_widget, user_checked, window): link = 'https://api.github.com/repos/giantas/sorter/releases/latest' try: with urllib.request.urlopen(link, timeout=5) as response: html = response.read() except urllib.request.URLError: message = 'Update check failed. Could not connect to the Internet.' msg_widget.config(text=message, relief=SUNKEN) self.logger.warning(message) else: items = json.loads(html.decode('utf-8')) latest_tag = items.get('tag_name') if latest_tag.strip('v') > SORTER_VERSION: items.get('html_url') body = items.get('body') features = body.replace('*', '') message = 'Update available!\n\nSorter {tag}.\n\n{feat} ....\n\nMore information on the'.format( tag=latest_tag, feat=features[:500]) msg_widget.config(text=message) self._official_website_label(master=window, window=window) else: if user_checked: message = 'No update found.\n\nYou have the latest version installed. Always stay up-to-date with fixes and new features.\n\nStay tuned for more!' msg_widget.config(text=message, relief=FLAT)
def get_tokens(): tokens = None try: # if we already have tokens, load and use them tokens = load_data_from_file(DATA_FILE)['tokens'] except: pass if not tokens: # if we need to get tokens, start the Native App authentication process tokens = do_native_app_authentication(CLIENT_ID, REDIRECT_URI, SCOPES) try: save_data_to_file(DATA_FILE, 'tokens', tokens) except: pass return tokens
def get_ip(): import subprocess return subprocess.check_output('dig +short myip.opendns.com @resolver1.opendns.com'.split()).strip().decode('ascii') # import socket # sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # sock.connect(('resolver1.opendns.com', 53)) # sock.send(b'\0\0\1\0\0\1\0\0\0\0\0\0\4myip\7opendns\3com\0\0\1\0\1') # resp = sock.recv(1000) # return '.'.join(str(b) for b in resp[-4:]) # import requests, re # data = requests.get('http://checkip.dyndns.com/').text # return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)
def _solve_google_captcha(self, resp): # set up the captcha page markup for parsing tree = fromstring(resp.text) # extract and request the captcha image #captchaUrl = 'https://ipv4.google.com' + tree.xpath('//img/@src')[0] #print(captchaUrl) resp = self.request('https://ipv4.google.com' + tree.xpath('//img/@src')[0], redirect=False, cookiejar=self.cookiejar, agent=self.user_agent) # store the captcha image to the file system with open('/tmp/111.jpg','w') as fp: fp.write(resp.raw) fp.flush() print(fp.name) # open the captcha image for viewing in gui environments w = webbrowser.get() w.open('file://' + fp.name) self.alert(fp.name) _payload = {'captcha':raw_input('[CAPTCHA] Answer: ')} # temporary captcha file removed on close # extract the form elements for the capctah answer request form = tree.xpath('//form[@action="index"]')[0] for x in ['q', 'continue', 'submit']: _payload[x] = form.xpath('//input[@name="%s"]/@value' % (x))[0] # send the captcha answer return self.request('https://ipv4.google.com/sorry/CaptchaRedirect', payload=_payload, cookiejar=self.cookiejar, agent=self.user_agent)
def start(self): handler = self.handleRequest if config.debug: # Auto reload UiRequest on change from Debug import DebugReloader DebugReloader(self.reload) # Werkzeug Debugger try: from werkzeug.debug import DebuggedApplication handler = DebuggedApplication(self.handleRequest, evalex=True) except Exception, err: self.log.info("%s: For debugging please download Werkzeug (http://werkzeug.pocoo.org/)" % err) from Debug import DebugReloader self.log.write = lambda msg: self.log.debug(msg.strip()) # For Wsgi access.log self.log.info("--------------------------------------") self.log.info("Web interface: http://%s:%s/" % (config.ui_ip, config.ui_port)) self.log.info("--------------------------------------") if config.open_browser: logging.info("Opening browser: %s...", config.open_browser) import webbrowser if config.open_browser == "default_browser": browser = webbrowser.get() else: browser = webbrowser.get(config.open_browser) browser.open("http://%s:%s" % (config.ui_ip if config.ui_ip != "*" else "127.0.0.1", config.ui_port), new=2) self.server = WSGIServer((self.ip.replace("*", ""), self.port), handler, handler_class=UiWSGIHandler, log=self.log) self.server.sockets = {} try: self.server.serve_forever() except Exception, err: self.log.error("Web interface bind error, must be running already, exiting.... %s" % err) sys.modules["main"].file_server.stop() self.log.debug("Stopped.")
def mainPythonWebbrowserFromExe(url, browser_exe=""): import webbrowser browser_type = '"%s"' % browser_exe + ' \%s' browser = webbrowser.get(browser_type) browser.open(url) ## Python????????????Web???????.
def open_browser(url: str, browser: str = None) -> None: """Open web browser.""" if '--open-browser' in sys.argv: # Remove open browser to prevent making new tab on autoreload sys.argv.remove('--open-browser') if browser is None: browser = config.browser if browser in _browsers: webbrowser.get(browser).open(url) else: webbrowser.open(url)
def fetchStreamURL(video_id): cdn_url = "http://getcdn.hotstar.com/AVS/besc?action=GetCDN&asJson=Y&channel=TABLET&id=" + video_id + "&type=VOD" response = r.get(cdn_url) if str(response) == '<Response [200]>': json_response = json.loads(response.text.encode('utf-8')) stream_url = json_response['resultObj']['src'].encode('utf-8') else: print('HTTP Error. Unable to connect to Hotstar. Exiting.\n') sys.exit(0) return stream_url
def doubleClick(self): row = self.table.selectionModel().selectedRows() index=[] for i in row: index.append(i.row()) url=self.table.item(index[0],0).text() taray?c?=self.table.item(index[0],2).text() if taray?c? == "mozilla-fireofox": webbrowser.get("firefox").open_new_tab(url) elif taray?c? == "google-chrome": webbrowser.get('google-chrome').open_new_tab(url)
def download(probID, path=pathlib.Path().cwd(), website=None): global websiteObject login(website) path = pathlib.Path(path) url = websiteObject.get_question(probID) html = requests.get(url).text question_file = open(path / (probID + ".html"), 'w') question_file.write(html) question_file.close()
def open_question(probID, web=None): global pref_manager global websiteObject login() if webbrowser is None: web = pref_manager.get("browser") try: browser = webbrowser.get(web) except webbrowser.Error: print("Invalid browser") return browser.open(websiteObject.get_question(probID))
def open_game(browser, url): return webbrowser.get(browser).open(url)
def keypress(self, size, key): if key in {'down', 'n', 'N'}: self.answer_text.next_ans() elif key in {'up', 'b', 'B'}: self.answer_text.prev_ans() elif key in {'o', 'O'}: import webbrowser if sys.platform.startswith('darwin'): browser = webbrowser.get('safari') else: browser = webbrowser.get() print_warning("Opening in your browser...") browser.open(self.url) elif key == 'left': global question_post global question_page question_post = None if question_page is None: sys.exit(0) else: LOOP.widget = question_page elif key == 'window resize': screenHeight, screenWidth = subprocess.check_output(['stty', 'size']).split() if self.screenHeight != screenHeight: self._invalidate() answer_frame = self.makeFrame(self.data) urwid.WidgetWrap.__init__(self, answer_frame)
def set_answer(self): """ We must use a box adapter to get the text to scroll when this widget is already in a Pile from the main question page. Scrolling is necessary for long answers which are longer than the length of the terminal. """ self.content = [('less-important', 'Answer: ')] + self.answers[self.index].split("\n") self._w = ScrollableTextBox(self.content)
def set_description(self): """ We must use a box adapter to get the text to scroll when this widget is already in a Pile from the main question page. Scrolling is necessary for long questions which are longer than the length of the terminal. """ self.content = self.description.strip("\n").split("\n") self._w = ScrollableTextBox(self.content)
def get_questions_for_query(query, count=10): """ Fetch questions for a query using stackoverflow default search mechanism. Returned question urls are relative to SO homepage. At most 10 questions are returned. (Can be altered by passing count) :param query: User-entered query string :return: list of [ (question_text, question_description, question_url) ] """ questions = [] randomheaders() search_res = requests.get(soqurl + query, headers=header) captchacheck(search_res.url) soup = BeautifulSoup(search_res.text, 'html.parser') try: soup.find_all("div", class_="question-summary")[0] # For explicitly raising exception except IndexError: print_warning("No results found...") sys.exit(0) tmp = (soup.find_all("div", class_="question-summary")) tmp1 = (soup.find_all("div", class_="excerpt")) i = 0 while (i < len(tmp)): if i == count: break # limiting results question_text = ' '.join((tmp[i].a.get_text()).split()) question_text = question_text.replace("Q: ", "") question_desc = (tmp1[i].get_text()).replace("'\r\n", "") question_desc = ' '.join(question_desc.split()) question_local_url = tmp[i].a.get("href") questions.append((question_text, question_desc, question_local_url)) i = i + 1 return questions
def fixGoogleURL(url): """ Fixes the url extracted from HTML when performing a google search :param url: :return: Correctly formatted URL to be used in requests.get """ if "&sa=" in url: url=url.split("&")[0] if "/url?q=" in url[0:7]: url = url[7:] #Removes the "/url?q=" prefix if url[:30] == "http://www.google.com/url?url=": #Used to get rid of this header and just retrieve the Stack Overflow link url = url[30:] if "http" not in url[:4]: url = "https://" + url #Add the protocol if it doesn't already exist #Makes sure that we stay in the questions section of Stack Overflow if not bool(re.search("/questions/[0-9]+", url)) and not bool(re.search("\.com/a/[0-9]", url)): return None if url[:17] == "https:///url?url=": #Resolves rare bug in which this is a prefix url = url[17:] return url
def retrieveSavedProfile(): """ Retrieves the user's saved profile after a "socli -u" command. Asks the user to enter a User ID and saves it if a previous file is not found. :return: The user's ID as an integer """ global data_file global app_data user = None try: load_datafile() if "user" in app_data: user = app_data["user"] else: raise FileNotFoundError # Manually raising to get value except JSONDecodeError: # This maybe some write failures del_datafile() print_warning("Error in parsing the data file, it will be now deleted. Please rerun the " "socli -u command.") exit(1) except FileNotFoundError: print_warning("Default user not set...\n") try: # Code to execute when first time user runs socli -u app_data['user'] = int(inputs("Enter your Stackoverflow User ID: ")) save_datafile() user = app_data['user'] print_green("\nUserID saved...\n") except ValueError: print_warning("\nUser ID must be an integer.") print( "\nFollow the instructions on this page to get your User ID: http://meta.stackexchange.com/a/111130") exit(1) return user
def process_item(self, item, spider): """Drop items not fitting parameters. Open in browser if specified. Return accepted items.""" if self._skip_list and str(item['id']) in self._skip_list: raise DropItem('Item in skip list: {}'.format(item['id'])) if self._minimum_monthly_discount and 'monthly_discount' in item: if item['monthly_discount'] < self._minimum_monthly_discount: raise DropItem('Monthly discount too low: {}'.format(item['monthly_discount'])) if self._minimum_weekly_discount and 'weekly_discount' in item: if item['weekly_discount'] < self._minimum_monthly_discount: raise DropItem('Weekly discount too low: {}'.format(item['weekly_discount'])) # check regexes if self._cannot_have_regex: for f in self._fields_to_check: v = str(item[f].encode('ASCII', 'replace')) if self._cannot_have_regex.search(v): raise DropItem('Found: {}'.format(self._cannot_have_regex.pattern)) if self._must_have_regex: has_must_haves = False for f in self._fields_to_check: v = str(item[f].encode('ASCII', 'replace')) if self._must_have_regex.search(v): has_must_haves = True break if not has_must_haves: raise DropItem('Not Found: {}'.format(self._must_have_regex.pattern)) # open in browser if self._web_browser: webbrowser.get(self._web_browser).open(item['url']) return item
def refresh_token(): from .libs import auth settings = setting.load() if not settings["use_oauth2"]: return False default_project_value = settings["default_project_value"] is_sandbox = default_project_value["is_sandbox"] if "refresh_token" not in default_project_value: print("refresh token missing") return False 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 = default_project_value["refresh_token"] # print(refresh_token) response_json = oauth.refresh_token(refresh_token) # print(response_json) if "error" in response_json: return False if "refresh_token" not in response_json: response_json["refresh_token"] = refresh_token save_session(response_json) print("------->refresh_token ok!") return True ########################################################################################## #Sublime Util ##########################################################################################
def get_soql_sobject(soql_str): soql = del_comment(soql_str) # match = re.match("select\s+\*\s+from[\s\t]+(\w+)([\t\s\S]*)", soql, re.I|re.M) match = re.match("select\\s+([\\w\\n,.:_\\s]*|\*)\\s+from[\s\t]+(\w+)([\t\s\S]*)", soql, re.I|re.M) sobject = "" if match: sobject = match.group(2) # print('------>' + match.group(0)) # print('------>' + match.group(1)) # print('------>' + match.group(2)) # print('------>' + match.group(3)) return sobject # get soql fields from soql,return list
def open_in_default_browser(url): browser_map = setting.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 ##########################################################################################
def setbrowser(browser=None): """ Registers the given browser and saves it as the module default. This is used to control which browser is used to display the plot. The argument should be a value that can be passed to webbrowser.get() to obtain a browser. If no argument is given, the default is reset to the system default. webbrowser provides some predefined browser names, including: 'firefox' 'opera' If the browser string contains '%s', it is interpreted as a literal browser command line. The URL will be substituted for '%s' in the command. For example: 'google-chrome %s' 'cmd "start iexplore.exe %s"' See the webbrowser documentation for more detailed information. Note: Safari does not reliably work with the webbrowser module, so we recommend using a different browser. """ global _browser if browser is None: _browser = None # Use system default else: webbrowser.register(browser, None, webbrowser.get(browser)) _browser = browser
def openinbrowser(url, browser=None): if browser is None: browser = _browser webbrowser.get(browser).open(url) # Create a temporary file that will be removed at exit # Returns a path to the file