当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.ex函数代码示例

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


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

示例1: _request

    def _request(self, method='get', params=None, data=None, files=None, **kwargs):

        params = params or {}

        if time.time() > self.last_time + 1800 or not self.auth:
            self.last_time = time.time()
            self._get_auth()

        logger.log('%s: sending %s request to %s with ...' % (self.name, method.upper(), self.url), logger.DEBUG)
        lines = [('params', (str(params), '')[not params]),
                 ('data', (str(data), '')[not data]),
                 ('files', (str(files), '')[not files]),
                 ('json', (str(kwargs.get('json')), '')[not kwargs.get('json')])]
        m, c = 300, 100
        type_chunks = [(linetype, [ln[i:i + c] for i in range(0, min(len(ln), m), c)]) for linetype, ln in lines if ln]
        for (arg, chunks) in type_chunks:
            output = []
            nch = len(chunks) - 1
            for i, seg in enumerate(chunks):
                if nch == i and 'files' == arg:
                    sample = ' ..excerpt(%s/%s)' % (m, len(lines[2][1]))
                    seg = seg[0:c - (len(sample) - 2)] + sample
                output += ['%s: request %s= %s%s%s' % (self.name, arg, ('', '..')[bool(i)], seg, ('', '..')[i != nch])]
            for out in output:
                logger.log(out, logger.DEBUG)

        if not self.auth:
            logger.log('%s: Authentication Failed' % self.name, logger.ERROR)
            return False
        try:
            response = self.session.__getattribute__(method)(self.url, params=params, data=data, files=files,
                                                             timeout=kwargs.pop('timeout', 120), verify=False, **kwargs)
        except requests.exceptions.ConnectionError as e:
            logger.log('%s: Unable to connect %s' % (self.name, ex(e)), logger.ERROR)
            return False
        except (requests.exceptions.MissingSchema, requests.exceptions.InvalidURL):
            logger.log('%s: Invalid Host' % self.name, logger.ERROR)
            return False
        except requests.exceptions.HTTPError as e:
            logger.log('%s: Invalid HTTP Request %s' % (self.name, ex(e)), logger.ERROR)
            return False
        except requests.exceptions.Timeout as e:
            logger.log('%s: Connection Timeout %s' % (self.name, ex(e)), logger.ERROR)
            return False
        except Exception as e:
            logger.log('%s: Unknown exception raised when sending torrent to %s: %s' % (self.name, self.name, ex(e)),
                       logger.ERROR)
            return False

        if 401 == response.status_code:
            logger.log('%s: Invalid Username or Password, check your config' % self.name, logger.ERROR)
            return False

        if response.status_code in http_error_code.keys():
            logger.log('%s: %s' % (self.name, http_error_code[response.status_code]), logger.DEBUG)
            return False

        logger.log('%s: Response to %s request is %s' % (self.name, method.upper(), response.text), logger.DEBUG)

        return response
开发者ID:JackDandy,项目名称:SickGear,代码行数:60,代码来源:generic.py

示例2: findSeason

def findSeason(show, season):

    logger.log(u"Searching for stuff we need from "+show.name+" season "+str(season))

    foundResults = {}

    didSearch = False

    for curProvider in providers.sortedProviderList():

        if not curProvider.isActive():
            continue

        try:
            curResults = curProvider.findSeasonResults(show, season)

            # make a list of all the results for this provider
            for curEp in curResults:

                # skip non-tv crap
                curResults[curEp] = filter(lambda x:  show_name_helpers.filterBadReleases(x.name, show) and show_name_helpers.isGoodResult(x.name, show), curResults[curEp])

                if curEp in foundResults:
                    foundResults[curEp] += curResults[curEp]
                else:
                    foundResults[curEp] = curResults[curEp]

        except exceptions.AuthException, e:
            logger.log(u"Authentication error: "+ex(e), logger.ERROR)
            continue
        except Exception, e:
            logger.log(u"Error while searching "+curProvider.name+", skipping: "+ex(e), logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)
            continue
开发者ID:DanCooper,项目名称:Sick-Beard,代码行数:34,代码来源:search.py

示例3: action

    def action(self, query, args=None):

        with db_lock:

            if query is None:
                return

            sqlResult = None
            attempt = 0

            while attempt < 5:
                try:
                    if args is None:
                        logger.log(self.filename + ': ' + query, logger.DB)
                        sqlResult = self.connection.execute(query)
                    else:
                        logger.log(self.filename + ': ' + query + ' with args ' + str(args), logger.DB)
                        sqlResult = self.connection.execute(query, args)
                    self.connection.commit()
                    # get out of the connection attempt loop since we were successful
                    break
                except sqlite3.OperationalError as e:
                    if 'unable to open database file' in e.args[0] or 'database is locked' in e.args[0]:
                        logger.log(u'DB error: ' + ex(e), logger.WARNING)
                        attempt += 1
                        time.sleep(1)
                    else:
                        logger.log(u'DB error: ' + ex(e), logger.ERROR)
                        raise
                except sqlite3.DatabaseError as e:
                    logger.log(u'Fatal error executing query: ' + ex(e), logger.ERROR)
                    raise

            return sqlResult
开发者ID:Apocrathia,项目名称:SickGear,代码行数:34,代码来源:db.py

示例4: _makeURL

    def _makeURL(self, result):
        urls = []
        filename = u''
        if result.url.startswith('magnet'):
            try:
                torrent_hash = re.findall('urn:btih:([\w]{32,40})', result.url)[0].upper()
                torrent_name = re.findall('dn=([^&]+)', result.url)[0]

                if len(torrent_hash) == 32:
                    torrent_hash = b16encode(b32decode(torrent_hash)).upper()

                if not torrent_hash:
                    logger.log("Unable to extract torrent hash from magnet: " + ex(result.url), logger.ERROR)
                    return (urls, filename)

                urls = [x.format(torrent_hash=torrent_hash, torrent_name=torrent_name) for x in self.btCacheURLS]
            except:
                logger.log("Unable to extract torrent hash or name from magnet: " + ex(result.url), logger.ERROR)
                return (urls, filename)
        else:
            urls = [result.url]

        if self.providerType == GenericProvider.TORRENT:
            filename = ek.ek(os.path.join, sickbeard.TORRENT_DIR,
                             helpers.sanitizeFileName(result.name) + '.' + self.providerType)

        elif self.providerType == GenericProvider.NZB:
            filename = ek.ek(os.path.join, sickbeard.NZB_DIR,
                             helpers.sanitizeFileName(result.name) + '.' + self.providerType)

        return (urls, filename)
开发者ID:pixatintes,项目名称:SickRage,代码行数:31,代码来源:generic.py

示例5: searchForNeededEpisodes

def searchForNeededEpisodes():

    logger.log(u"Searching all providers for any needed episodes")

    foundResults = {}

    didSearch = False

    # ask all providers for any episodes it finds
    for curProvider in providers.sortedProviderList():

        if not curProvider.isActive():
            continue

        curFoundResults = {}

        try:
            curFoundResults = curProvider.searchRSS()
        except exceptions.AuthException, e:
            logger.log(u"Authentication error: "+ex(e), logger.ERROR)
            continue
        except Exception, e:
            logger.log(u"Error while searching "+curProvider.name+", skipping: "+ex(e), logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)
            continue
开发者ID:DanCooper,项目名称:Sick-Beard,代码行数:25,代码来源:search.py

示例6: action

    def action(self, query, args=None):

        with db_lock:

            if query == None:
                return

            sqlResult = None
            attempt = 0

            while attempt < 5:
                time.sleep(0.01)
                try:
                    if args == None:
                        logger.log(self.filename + ": " + query, logger.DB)
                        sqlResult = self.connection.execute(query)
                    else:
                        logger.log(self.filename + ": " + query + " with args " + str(args), logger.DB)
                        sqlResult = self.connection.execute(query, args)
                    self.connection.commit()
                    # get out of the connection attempt loop since we were successful
                    break
                except sqlite3.OperationalError, e:
                    if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]:
                        logger.log(u"DB error: " + ex(e), logger.WARNING)
                        attempt += 1
                        time.sleep(1)
                    else:
                        logger.log(u"DB error: " + ex(e), logger.ERROR)
                        raise
                except sqlite3.DatabaseError, e:
                    logger.log(u"Fatal error executing query: " + ex(e), logger.ERROR)
                    raise
开发者ID:3ne,项目名称:SickRage,代码行数:33,代码来源:db.py

示例7: test_notify

    def test_notify(self, username, disable_ssl, blacklist_name=None):
        """
        Sends a test notification to trakt with the given authentication info and returns a boolean
        representing success.

        api: The api string to use
        username: The username to use
        password: The password to use
        blacklist_name: slug of trakt list used to hide not interested show

        Returns: True if the request succeeded, False otherwise
        """
        try:
            trakt_api = TraktAPI(disable_ssl, sickbeard.TRAKT_TIMEOUT)
            trakt_api.validateAccount()
            if blacklist_name and blacklist_name is not None:
                trakt_lists = trakt_api.traktRequest("users/" + username + "/lists")
                found = False
                for trakt_list in trakt_lists:
                    if (trakt_list['ids']['slug'] == blacklist_name):
                        return "Test notice sent successfully to Trakt"
                if not found:
                    return "Trakt blacklist doesn't exists"
            else:
                return "Test notice sent successfully to Trakt"
        except (traktException, traktAuthException, traktServerBusy) as e:
            logger.log(u"Could not connect to Trakt service: %s" % ex(e), logger.WARNING)
            return "Test notice failed to Trakt: %s" % ex(e)
开发者ID:Buttink,项目名称:SickRage,代码行数:28,代码来源:trakt.py

示例8: _run_extra_scripts

    def _run_extra_scripts(self, ep_obj):
        """
        Executes any extra scripts defined in the config.

        ep_obj: The object to use when calling the extra script
        """
        for curScriptName in sickbeard.EXTRA_SCRIPTS:

            # generate a safe command line string to execute the script and provide all the parameters
            script_cmd = [piece for piece in re.split("( |\\\".*?\\\"|'.*?')", curScriptName) if piece.strip()]
            script_cmd[0] = ek.ek(os.path.abspath, script_cmd[0])
            self._log(u"Absolute path to script: " + script_cmd[0], logger.DEBUG)

            script_cmd = script_cmd + [ep_obj.location, self.file_path, str(ep_obj.show.indexerid), str(ep_obj.season),
                                       str(ep_obj.episode), str(ep_obj.airdate)]

            # use subprocess to run the command and capture output
            self._log(u"Executing command " + str(script_cmd))
            try:
                p = subprocess.Popen(script_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT, cwd=sickbeard.PROG_DIR)
                out, err = p.communicate()  # @UnusedVariable
                self._log(u"Script result: " + str(out), logger.DEBUG)

            except OSError, e:
                self._log(u"Unable to run extra_script: " + ex(e))

            except Exception, e:
                self._log(u"Unable to run extra_script: " + ex(e))
开发者ID:WoLpH,项目名称:SickBeard-TVRage,代码行数:29,代码来源:postProcessor.py

示例9: findSeason

def findSeason(show, season):

    myDB = db.DBConnection()
    allEps = [int(x["episode"]) for x in myDB.select("SELECT episode FROM tv_episodes WHERE showid = ? AND season = ?", [show.tvdbid, season])]
    logger.log(u"Episode list: "+str(allEps), logger.DEBUG)

    
    reallywanted=[]
    notwanted=[]
    finalResults = []
    for curEpNum in allEps:
        sqlResults = myDB.select("SELECT status FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ?", [show.tvdbid, season, curEpNum])
        epStatus = int(sqlResults[0]["status"])
        if epStatus ==3:
            reallywanted.append(curEpNum)
        else:
            notwanted.append(curEpNum)
    if notwanted != []:
        for EpNum in reallywanted:
            showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, show.tvdbid)
            episode = showObj.getEpisode(season, EpNum)
            res=findEpisode(episode, manualSearch=True)
            snatchEpisode(res)
        return
    else:
        logger.log(u"Searching for stuff we need from "+show.name+" season "+str(season))
    
        foundResults = {}
    
        didSearch = False
    
        for curProvider in providers.sortedProviderList():
    
            if not curProvider.isActive():
                continue
    
            try:
                curResults = curProvider.findSeasonResults(show, season)
    
                # make a list of all the results for this provider
                for curEp in curResults:
    
                    # skip non-tv crap
                    curResults[curEp] = filter(lambda x:  show_name_helpers.filterBadReleases(x.name) and show_name_helpers.isGoodResult(x.name, show), curResults[curEp])
    
                    if curEp in foundResults:
                        foundResults[curEp] += curResults[curEp]
                    else:
                        foundResults[curEp] = curResults[curEp]
    
            except exceptions.AuthException, e:
                logger.log(u"Authentication error: "+ex(e), logger.ERROR)
                continue
            except Exception, e:
                logger.log(u"Error while searching "+curProvider.name+", skipping: "+ex(e), logger.DEBUG)
                logger.log(traceback.format_exc(), logger.DEBUG)
                continue
    
            didSearch = True
开发者ID:ClubSoundZ,项目名称:Sick-Beard,代码行数:59,代码来源:search.py

示例10: _request

    def _request(self, method='get', params={}, data=None, files=None):
        response = None
        if time.time() > self.last_time + 1800 or not self.auth:
            self.last_time = time.time()
            self._get_auth()

        logger.log(
            self.name + u': Requested a ' + method.upper() +
            ' connection to url ' + self.url + ' with Params= ' + str(params) +
            ' Data=' + str(data if data else 'None')[0:99] +
            ('...' if len(data if data else 'None') > 200 else ''),
            logger.DEBUG
        )

        logger.log(
            self.name + u': Requested a ' + method.upper() +
            ' connection to url ' + self.url + ' with Params= ' + str(params) +
            ((' Data=' + str(data)[0:100] + ('...' if len(data) > 100 else ''))
             if data is not None else ''),
            logger.DEBUG
        )

        if not self.auth:
            logger.log(self.name + u': Authentication Failed', logger.ERROR)
            return False
        try:
            response = self.session.__getattribute__(method)(self.url, params=params, data=data, files=files,
                                                                  timeout=120, verify=False)
        except requests.exceptions.ConnectionError as e:
            logger.log(self.name + u': Unable to connect ' + ex(e), logger.ERROR)
            return False
        except (requests.exceptions.MissingSchema, requests.exceptions.InvalidURL):
            logger.log(self.name + u': Invalid Host', logger.ERROR)
            return False
        except requests.exceptions.HTTPError as e:
            logger.log(self.name + u': Invalid HTTP Request ' + ex(e), logger.ERROR)
            return False
        except requests.exceptions.Timeout as e:
            logger.log(self.name + u': Connection Timeout ' + ex(e), logger.ERROR)
            return False
        except Exception as e:
            logger.log(self.name + u': Unknown exception raised when sending torrent to ' + self.name + ': ' + ex(e),
                       logger.ERROR)
            return False

        if response.status_code == 401:
            logger.log(self.name + u': Invalid Username or Password, check your config', logger.ERROR)
            return False

        if response.status_code in http_error_code.keys():
            logger.log(self.name + u': ' + http_error_code[response.status_code], logger.DEBUG)
            return False

        logger.log(self.name + u': Response to ' + method.upper() + ' request is ' + response.text, logger.DEBUG)

        return response
开发者ID:Apocrathia,项目名称:SickGear,代码行数:56,代码来源:generic.py

示例11: mass_action

    def mass_action(self, querylist, logTransaction=False):

        with db_lock:
            # remove None types
            querylist = [i for i in querylist if i != None]

            if querylist == None:
                return

            sqlResult = []
            attempt = 0

            # Transaction
            self.connection.isolation_level = None
            self.connection.execute('BEGIN')

            while attempt < 5:
                try:

                    for qu in querylist:
                        if len(qu) == 1:
                            if logTransaction:
                                logger.log(qu[0], logger.DEBUG)
                            sqlResult.append(self.connection.execute(qu[0]))
                        elif len(qu) > 1:
                            if logTransaction:
                                logger.log(qu[0] + " with args " + str(qu[1]),
                                           logger.DEBUG)
                            sqlResult.append(
                                self.connection.execute(qu[0], qu[1]))

                    self.connection.commit()

                    logger.log(
                        u"Transaction with " + str(len(querylist)) +
                        u" queries executed", logger.DEBUG)
                    return sqlResult
                except sqlite3.OperationalError, e:
                    sqlResult = []
                    if self.connection:
                        self.connection.rollback()
                    if "unable to open database file" in e.args[
                            0] or "database is locked" in e.args[0]:
                        logger.log(u"DB error: " + ex(e), logger.WARNING)
                        attempt += 1
                        time.sleep(0.02)
                    else:
                        logger.log(u"DB error: " + ex(e), logger.ERROR)
                        raise
                except sqlite3.DatabaseError, e:
                    sqlResult = []
                    if self.connection:
                        self.connection.rollback()
                    logger.log(u"Fatal error executing query: " + ex(e),
                               logger.ERROR)
                    raise
开发者ID:Jaerin,项目名称:SickRage,代码行数:56,代码来源:db.py

示例12: _api_call

 def _api_call(self, apikey, params={}, results_per_page=1000, offset=0):
     server = jsonrpclib.Server('http://api.btnapps.net')
     
     search_results ={} 
     try:
         search_results = server.getTorrentsSearch(apikey, params, int(results_per_page), int(offset))
     except jsonrpclib.jsonrpc.ProtocolError, error:
         logger.log(u"JSON-RPC protocol error while accessing BTN API: " + ex(error), logger.ERROR)
         search_results = {'api-error': ex(error)}
         return search_results
开发者ID:ChrisiB,项目名称:Sick-Beard,代码行数:10,代码来源:btn.py

示例13: send_torrent

    def send_torrent(self, result):

        r_code = False

        logger.log('Calling %s Client' % self.name, logger.DEBUG)

        if not self._get_auth():
            logger.log('%s: Authentication Failed' % self.name, logger.ERROR)
            return r_code

        try:
            # Sets per provider seed ratio
            result.ratio = result.provider.seed_ratio()

            result = self._get_torrent_hash(result)
        except Exception as e:
            logger.log('Bad torrent data: hash is %s for [%s]' % (result.hash, result.name), logger.ERROR)
            logger.log('Exception raised when checking torrent data: %s' % (ex(e)), logger.DEBUG)
            return r_code

        try:
            if result.url.startswith('magnet'):
                r_code = self._add_torrent_uri(result)
            else:
                r_code = self._add_torrent_file(result)

            if not r_code:
                logger.log('%s: Unable to send torrent to client' % self.name, logger.ERROR)
                return False

            if not self._set_torrent_pause(result):
                logger.log('%s: Unable to set the pause for torrent' % self.name, logger.ERROR)

            if not self._set_torrent_label(result):
                logger.log('%s: Unable to set the label for torrent' % self.name, logger.ERROR)

            if not self._set_torrent_ratio(result):
                logger.log('%s: Unable to set the ratio for torrent' % self.name, logger.ERROR)

            if not self._set_torrent_seed_time(result):
                logger.log('%s: Unable to set the seed time for torrent' % self.name, logger.ERROR)

            if not self._set_torrent_path(result):
                logger.log('%s: Unable to set the path for torrent' % self.name, logger.ERROR)

            if 0 != result.priority and not self._set_torrent_priority(result):
                logger.log('%s: Unable to set priority for torrent' % self.name, logger.ERROR)

        except Exception as e:
            logger.log('%s: Failed sending torrent: %s - %s' % (self.name, result.name, result.hash), logger.ERROR)
            logger.log('%s: Exception raised when sending torrent: %s' % (self.name, ex(e)), logger.DEBUG)
            return r_code

        return r_code
开发者ID:JackDandy,项目名称:SickGear,代码行数:54,代码来源:generic.py

示例14: _parse_string

    def _parse_string(self, name):

        if not name:
            return None

        for (cur_regex_name, cur_regex) in self.compiled_regexes:
            match = cur_regex.match(name)

            if not match:
                continue

            result = ParseResult(name)
            result.which_regex = [cur_regex_name]

            named_groups = match.groupdict().keys()

            if 'series_name' in named_groups:
                result.series_name = match.group('series_name')
                if result.series_name:
                    result.series_name = self.clean_series_name(result.series_name)

            if 'season_num' in named_groups:
                tmp_season = int(match.group('season_num'))
                if cur_regex_name == 'bare' and tmp_season in (19, 20):
                    continue
                result.season_number = tmp_season

            if 'ep_num' in named_groups:
                try:
                    ep_num = self._convert_number(match.group('ep_num'))
                    if 'extra_ep_num' in named_groups and match.group('extra_ep_num'):
                        result.episode_numbers = range(ep_num, self._convert_number(match.group('extra_ep_num')) + 1)
                    else:
                        result.episode_numbers = [ep_num]

                except ValueError, e:
                    raise InvalidNameException(ex(e))

            if 'air_year' in named_groups and 'air_month' in named_groups and 'air_day' in named_groups:
                year = int(match.group('air_year'))
                month = int(match.group('air_month'))
                day = int(match.group('air_day'))

                # make an attempt to detect YYYY-DD-MM formats
                if month > 12:
                    tmp_month = month
                    month = day
                    day = tmp_month

                try:
                    result.air_date = datetime.date(year, month, day)
                except ValueError, e:
                    raise InvalidNameException(ex(e))
开发者ID:PermaNulled,项目名称:SickBeard-XG,代码行数:53,代码来源:parser.py

示例15: _sabURLOpenSimple

def _sabURLOpenSimple(url):
    try:
        f = urllib.urlopen(url)
    except (EOFError, IOError) as e:
        logger.log(u"Unable to connect to SABnzbd: " + ex(e), logger.ERROR)
        return False, "Unable to connect"
    except moves.http_client.InvalidURL as e:
        logger.log(u"Invalid SABnzbd host, check your config: " + ex(e), logger.ERROR)
        return False, "Invalid SABnzbd host"
    if f is None:
        logger.log(u"No data returned from SABnzbd", logger.ERROR)
        return False, "No data returned from SABnzbd"
    else:
        return True, f
开发者ID:joshguerette,项目名称:SickGear,代码行数:14,代码来源:sab.py


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