python类get()的实例源码

UiServer.py 文件源码 项目:zeronet-debian 作者: bashrc 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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.")
web_browser.py 文件源码 项目:PyIntroduction 作者: tody411 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def mainPythonWebbrowserFromExe(url, browser_exe=""):
    import webbrowser
    browser_type = '"%s"' % browser_exe + ' \%s'
    browser = webbrowser.get(browser_type)
    browser.open(url)

## Python????????????Web???????.
base.py 文件源码 项目:wdom 作者: miyakogi 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
hotstar-hound.py 文件源码 项目:hotstar-hound 作者: baddymaster 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
anasayfa.py 文件源码 项目:browser-history-phyton 作者: sistem-progamlama 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
CLI.py 文件源码 项目:competitive-cli 作者: GDGVIT 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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()
CLI.py 文件源码 项目:competitive-cli 作者: GDGVIT 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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))
game_control.py 文件源码 项目:Controller-Hand 作者: ardamavi 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def open_game(browser, url):
    return webbrowser.get(browser).open(url)
socli.py 文件源码 项目:socli 作者: gautamkrishnar 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
socli.py 文件源码 项目:socli 作者: gautamkrishnar 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
socli.py 文件源码 项目:socli 作者: gautamkrishnar 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
socli.py 文件源码 项目:socli 作者: gautamkrishnar 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
socli.py 文件源码 项目:socli 作者: gautamkrishnar 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
socli.py 文件源码 项目:socli 作者: gautamkrishnar 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
pipelines.py 文件源码 项目:airbnb_scraper 作者: bashedev 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
util.py 文件源码 项目:SalesforceXyTools 作者: exiahuang 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
##########################################################################################
util.py 文件源码 项目:SalesforceXyTools 作者: exiahuang 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
util.py 文件源码 项目:SalesforceXyTools 作者: exiahuang 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
##########################################################################################
image.py 文件源码 项目:codingTheMatrix 作者: RestrictedZone 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
image.py 文件源码 项目:codingTheMatrix 作者: RestrictedZone 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号