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


Python logger.error函数代码示例

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


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

示例1: get_tags

def get_tags(limit):
    tagset = {}
    try:
        for code in Code.where():
            tag = code.tags
            if not tag:
                continue
            ts = tag.split(",")
            for t in ts:
                if tagset.has_key(t):
                    tagset[t] += 1
                else:
                    tagset[t] = 1

        for post in Post.where(status=1):
            tag = post.tags
            if not tag:
                continue
            ts = tag.split(",")
            for t in ts:
                if tagset.has_key(t):
                    tagset[t] += 1
                else:
                    tagset[t] = 1       
        sort_tags = sorted( tagset.items(),key=lambda d:d[1],reverse=True)
        print sort_tags
        return sort_tags[:limit]
    except Exception,e:
        logger.error("get tags error,%s"%e)
        raise e
开发者ID:jamiesun,项目名称:talkincode,代码行数:30,代码来源:store.py

示例2: package

def package(pkg_name, option="-y"):

	if pkg_name:
		command_line_str = "yum " + option + " install " + pkg_name
		if os.system(command_line_str)!=0:
			logger.error("exec: %s error" % (command_line_str))
			sys.exit(1)
开发者ID:jamesduan,项目名称:common_tools,代码行数:7,代码来源:resource.py

示例3: get_qty

    def get_qty(self):
        qty_res = [p.text for p in self.s.select(
            settings.WELL['qty_css_selector'])]

        try:
            # Extract product attributes: |Size|QTY|Weight|Unit_Price|Price
            qty_regex_result = re.findall(
                settings.WELL['qty_regex'], qty_res[0])
            assert(len(qty_regex_result) == 1)

            # Strip unnecessary stuff
            qty_regex_result[0] = re.sub(
                r"swatch_stock_list\[0\]='.*'; ", "", qty_regex_result[0])
            qty_regex_results = qty_regex_result[0].split(" ")

            # Second element is package quantity
            self.pkg_qty = qty_regex_results[1]

            try:
                # Calculate unit price
                self.unit_price = "%.2f" % (
                    (float)((self.current_price).strip('$')) / (float)(self.pkg_qty))
                # Reconvert to string by adding the $ sign
                self.unit_price = "$" + self.unit_price

            except ValueError as err:
                logger.error("Unable calculating price: %s" %
                             (err), exc_info=True)

        except (AssertionError, IndexError) as err:
            logger.error("Unable to get qty: %s" % (err), exc_info=True)
开发者ID:Drulex,项目名称:diaper_deals,代码行数:31,代码来源:product.py

示例4: fetch_result

 def fetch_result(self, cond={}):
     try:
         for item in self.db.Result.find(cond):
             yield item
     except errors.ServerSelectionTimeoutError as e:
         logger.error("timed out to fetch {0}".format(table))
         raise exceptions.ConnectionError("connecting timeout")
开发者ID:muma378,项目名称:datatang,代码行数:7,代码来源:database.py

示例5: fetch

 def fetch(self, table, cond):
     try:
         for item in getattr(self.db, table).find(cond):
             yield item
     except errors.ServerSelectionTimeoutError as e:
         logger.error("timed out to fetch {0}".format(table))
         raise exceptions.ConnectionError("connecting timeout")
开发者ID:muma378,项目名称:datatang,代码行数:7,代码来源:database.py

示例6: parse_data

    def parse_data(self):
        """Parse info for each product"""
        # Extract price information
        regular_price = self.s.select(
            settings.TOYSRUS['regular_price_css_selector'])

        try:
            # Sometimes regular price is lower than current
            assert(len(regular_price) <= 1)
            current_price = self.s.select(
                settings.TOYSRUS['current_price_css_selector'])
            assert(len(current_price) == 1)

            if(regular_price):
                self.regular_price = regular_price[0].text.strip()
            self.current_price = current_price[0].text.strip()
        except AssertionError as err:
            logger.error("Unable to get price: %s" % (err), exc_info=True)

        # Extract upc info
        upc = self.s.select(settings.TOYSRUS['upc_css_selector'])
        try:
            assert(len(upc) == 1)
            self.upc = upc[0].text.strip()
        except AssertionError as err:
            logger.error("Unable to get UPC code: %s" % (err), exc_info=True)

        # Extract qty and unit price info
        self.get_qty()

        # Extract size information
        self.get_size()
开发者ID:Drulex,项目名称:diaper_deals,代码行数:32,代码来源:product.py

示例7: sitemap_data

def sitemap_data():
    urlset = []
    try:
        for post in Post.where(status=1):
            lastmod_tmp = datetime.datetime.strptime(post.modified,"%Y-%m-%d %H:%M:%S")
            lastmod = lastmod_tmp.strftime("%Y-%m-%dT%H:%M:%SZ")
            url = dict(loc="http://www.talkincode.org/news/post/view/%s"%post.id,
                       lastmod=lastmod,chgfreq="daily")
            urlset.append(url)


        for code in Code.where():
            lastmod_tmp = datetime.datetime.strptime(code.create_time,"%Y-%m-%d %H:%M:%S")
            lastmod = lastmod_tmp.strftime("%Y-%m-%dT%H:%M:%SZ")
            url = dict(loc="http://www.talkincode.org/code/view/%s"%code.id,
                       lastmod=lastmod,chgfreq="monthly")
            urlset.append(url)       

        for proj in Project.where():
            lastmod_tmp = datetime.datetime.strptime(proj.created,"%Y-%m-%d %H:%M:%S")
            lastmod = lastmod_tmp.strftime("%Y-%m-%dT%H:%M:%SZ")
            url = dict(loc="http://www.talkincode.org/open/proj/view/%s"%proj.id,
                       lastmod=lastmod,chgfreq="monthly")
            urlset.append(url)                             
          
        return urlset
    except Exception,e:
        logger.error("login error,%s"%e)
        return []
开发者ID:jamiesun,项目名称:talkincode,代码行数:29,代码来源:store.py

示例8: parse_blocks

	def parse_blocks(self):		
		lineno, interval, intervals = 0, {}, []

		def block_ends(interval, intervals):
			interval['lineno'] = lineno
			intervals.append(interval)

		# iterator for MULTILINES_PATTERN
		mp_iter = CycleIterator(self.__pack(TextgridBlocksParser.PATTERN_KEYS, TextgridBlocksParser.MULTILINES_PATTERN))
		# iterator for BLOCK_PATTERN
		bp_iter = CycleIterator(self.__pack(TextgridBlocksParser.PATTERN_KEYS, TextgridBlocksParser.BLOCK_PATTERN))
		line_pattern = bp_iter.next()

		for line in self.lines:
			lineno += 1

			# always try to match the begining pattern at first to avoid missing a normal block 
			# therefore, reset the block parsing once a line was matched to the begining pattern
			# but unmatched to the current one.
			if not bp_iter.begins() and self.__match(bp_iter.head(), line):
				logger.error('unable to parse line %d, ignored' % (lineno-1))
				interval, line_pattern = {}, bp_iter.reset()

			# to match the pattern one by one until it ends
			if self.__match(line_pattern, line):
				self.__update(interval, line_pattern, line)

				# if the end of block was matched
				# block ends here for most situation
				if bp_iter.ends():
					block_ends(interval, intervals)
					interval = {}

			# when a text existed in multiple lines
			elif bp_iter.ends():
					# match the begining of text in multi-lines
					if self.__match(mp_iter.head(), line):
						self.__update(interval, mp_iter.head(), line)
						continue # should not to call the next block pattern

					# match the pattern of end line
					# block also may end here for multiple lines
					elif self.__match(mp_iter.tail(), line): 
						self.__update(interval, mp_iter.tail(), line, append=True)
						block_ends(interval, intervals)
						interval = {}

					# match the pattern without quotes
					else:
						# append the middle part of the text
						self.__update(interval, mp_iter.index(1), line, append=True)
						continue
			else:
				# does not match anything
				# logger.error('unable to parse line %d, ignored' % (lineno-1))
				continue
			
			line_pattern = bp_iter.next()	# match the next pattern

		return intervals
开发者ID:dyan0123,项目名称:Utils,代码行数:60,代码来源:parse_blocks.py

示例9: get_tests_groups_from_jenkins

def get_tests_groups_from_jenkins(runner_name, build_number, distros):
    runner_build = Build(runner_name, build_number)
    res = {}
    for b in runner_build.build_data['subBuilds']:

        if b['result'] is None:
            logger.debug("Skipping '{0}' job (build #{1}) because it's still "
                         "running...".format(b['jobName'], b['buildNumber'],))
            continue

        # Get the test group from the console of the job
        z = Build(b['jobName'], b['buildNumber'])
        console = z.get_job_console()
        groups = [keyword.split('=')[1]
                  for line in console
                  for keyword in line.split()
                  if 'run_tests.py' in line and '--group=' in keyword]
        if not groups:
            logger.error("No test group found in console of the job {0}/{1}"
                         .format(b['jobName'], b['buildNumber']))
            continue
        # Use the last group (there can be several groups in upgrade jobs)
        test_group = groups[-1]

        # Get the job suffix
        job_name = b['jobName']
        for distro in distros:
            if distro in job_name:
                sep = '.' + distro + '.'
                job_suffix = job_name.split(sep)[-1]
                break
        else:
            job_suffix = job_name.split('.')[-1]
        res[job_suffix] = test_group
    return res
开发者ID:mattymo,项目名称:fuel-qa,代码行数:35,代码来源:upload_cases_description.py

示例10: get_check_create_test_run

    def get_check_create_test_run(self, plan, cases):
        plan = self.project.plans.get(plan.id)
        suite_cases = self.suite.cases()
        run_name = self.get_run_name()
        runs = plan.runs.find_all(name=run_name)
        run = self.check_need_create_run(plan,
                                         runs,
                                         suite_cases)

        if run is None:
            logger.info('Run not found in plan "{}", create: "{}"'.format(
                plan.name, run_name))

            # Create new test run with cases from test suite
            suite_cases = self.get_suite_cases()

            if not suite_cases:
                logger.error('Empty test cases set.')
                return None

            # suite_cases = self.suite.cases.find(type_id=type_ids[0])
            run = Run(name=run_name,
                      description=self.run_description,
                      suite_id=self.suite.id,
                      milestone_id=self.milestone.id,
                      config_ids=[],
                      case_ids=[x.id for x in suite_cases]
                      )
            plan.add_run(run)
            logger.debug('Run created "{}"'.format(run_name))
        return run
开发者ID:ehles,项目名称:trep,代码行数:31,代码来源:reporter.py

示例11: r_file

def r_file(filename, mode=None, content="", action=""):

	is_exists_file = os.path.exists(filename)

	if action == "create":

		if is_exists_file:

			try:
				os.remove(filename)
				os.mknod(filename)
				logger.info("Create File Ok.")

				with open(filename , 'w+') as f:
					f.write(content)

			except OSError, e:
				logger.error("filename: %s " % (filename) + str(e) )
				sys.exit(1)
		else:

			try:
				os.mknod(filename)
				logger.info("Create File Ok.")

				with open(filename , 'w+') as f:
					f.write(content)

			except OSError, e:
				logger.error("filename: %s" % (filename) + str(e))
				sys.exit(1)
开发者ID:jamesduan,项目名称:common_tools,代码行数:31,代码来源:resource.py

示例12: weater

def weater(lat, lng, timezone, unit='celsius', weather_key_=weather_key):
    res = {}
    try:
        owm = pyowm.OWM(weather_key_)
        observation = owm.three_hours_forecast_at_coords(lat, lng)
    except Exception, e:
        logger.error("weater {0}".format(e.message))
开发者ID:sbres,项目名称:ShouldItakemyumbrella_bot,代码行数:7,代码来源:get_weater_api.py

示例13: exec_dcfg

	def exec_dcfg(self):

		# first exec support script to install system tables.
		try:
			logger.info("============MYSQL DEFAULT CONFIG===========")
			logger.info("install system db.")
			os.chdir(mysql_home)
			exec_command('./scripts/mysql_install_db --user=mysql')

			logger.info("copy boot script to correct directory.")
			exec_command('cp ' + mysql_boot_script + ' /etc/init.d/')

			# sed config
			exec_command('sed -i -e "46s/basedir=/basedir=\/opt\/magima\/mysql/g" /etc/init.d/mysql.server')

			exec_command('sed -i -e "47s/datadir=/datadir=\/opt\/magima\/mysql\/data/g" /etc/init.d/mysql.server')

			exec_command("/etc/init.d/mysql.server start")
			exec_command("/etc/init.d/mysql.server status")
			exec_command("/etc/init.d/mysql.server stop")
			logger.info("==============TOMCAT DEFAULT CONFIG==============")
			logger.info("copy tomcat bootscript to /etc/init.d/")
			exec_command("cp " + tomcat_bootstrap + " /etc/init.d/tomcat6")
			exec_command("sudo /etc/init.d/tomcat6 start")
			exec_command("sudo /etc/init.d/tomcat6 status")
			exec_command("sudo /etc/init.d/tomcat6 stop")

		except OSError , oserr:
			logger.error("os error: %s " % str(oserr))
			sys.exit(1)
开发者ID:jamesduan,项目名称:common_tools,代码行数:30,代码来源:dcfg.py

示例14: apply_transactions

def apply_transactions(transactions, auto=False):
    ''' Apply renaming transactions.
    apply_transactions(transactions)
    transactions = [(old_path, new_path),(old_path),(new_path),...]
    Manual review of transactions is required.
    '''
    if auto:
        logger.warning('Auto is On. No confirmation required.')
    print('='*30)
    if not transactions:
        logger.debug('NO TRANSACTIONS')
        sys.exit('No Transactions to apply.')
        return

    for t in transactions:
        print('[{}] > [{}]'.format(t[0].name, t[1].name))
    print('{} Transactions to apply. Renaming...'.format(len(transactions)))
    count = 0
    if auto or input('EXECUTE ? [y]\n>') == 'y':
        for src, dst in transactions:
            try:
                src.rename(dst)
            except:
                logger.error(sys.exc_info()[0].__name__)
                logger.error('Could not rename: [{}]>[{}]'.format(src, dst))
            else:
                logger.debug('[{}] renamed to [{}]'.format(src, dst))
                count += 1

        print('{} folders renamed.'.format(count))
开发者ID:gtalarico,项目名称:foldify,代码行数:30,代码来源:empty.py

示例15: discover_functions

    def discover_functions(self):
	self.self_cursor.execute("SELECT pro_oid,func_name,id FROM function_name WHERE {0}={1} AND alive".format(self.sub_fk,self.id))
	local_funcs=self.self_cursor.fetchall()
	try:
	    self.prod_cursor.execute("""SELECT p.oid AS pro_oid,p.proname AS funcname,p.proretset,t.typname,l.lanname
FROM pg_proc p
LEFT JOIN pg_namespace n ON n.oid = p.pronamespace
JOIN pg_type t ON p.prorettype=t.oid
JOIN pg_language l ON p.prolang=l.oid
WHERE (p.prolang <> (12)::oid)
AND n.oid=(SELECT oid FROM pg_namespace WHERE nspname='public')""")
	except Exception as e:
	    logger.error("Cannot execute function discovery query: {0}".format(e.pgerror))
	    return
	prod_funcs=self.prod_cursor.fetchall()
	for l_func in local_funcs:
	    for p_func in prod_funcs:
		if l_func[0]==p_func[0] and l_func[1]==p_func[1]:
		    break
	    else:
		logger.info("Retired function {0} in schema {1}".format(l_func[1],self.db_fields['sch_name']))
		old_func=FunctionName(l_func[2])
#		old_func.populate()
		old_func.retire()
	for p_func in  prod_funcs:
	    for l_func in local_funcs:
		if p_func[0]==l_func[0] and p_func[1]==l_func[1]:
		    break
	    else:
		logger.info("Created new function: {0} in schema {1}".format(p_func[1],self.db_fields['sch_name']))
		new_func=FunctionName()
		new_func.set_fields(sn_id=self.id,pro_oid=p_func[0],func_name=p_func[1],proretset=p_func[2],prorettype=p_func[3],prolang=p_func[4])
		new_func.create()
		new_func.truncate()
开发者ID:arsen-movsesyan,项目名称:pg-Mon,代码行数:34,代码来源:objects.py


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