• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python utils.LOGGER类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: _execute

    def _execute(self, options, args):
        """Apply mincss the generated site."""
        output_folder = self.site.config["OUTPUT_FOLDER"]
        if Processor is None:
            LOGGER.warn("To use the mincss command," ' you have to install the "mincss" package.')
            return

        p = Processor(preserve_remote_urls=False)
        urls = []
        css_files = {}
        for root, dirs, files in os.walk(output_folder):
            for f in files:
                url = os.path.join(root, f)
                if url.endswith(".css"):
                    fname = os.path.basename(url)
                    if fname in css_files:
                        LOGGER.error("You have two CSS files with the same name and that confuses me.")
                        sys.exit(1)
                    css_files[fname] = url
                if not f.endswith(".html"):
                    continue
                urls.append(url)
        p.process(*urls)
        for inline in p.links:
            fname = os.path.basename(inline.href)
            with open(css_files[fname], "wb+") as outf:
                outf.write(inline.after)
开发者ID:verbalshadow,项目名称:nikola,代码行数:27,代码来源:mincss.py


示例2: sort_tags

def sort_tags(site, filepaths, dry_run=False):
    """ Sorts all the tags in the given list of posts.

        $ nikola tags --sort posts/*.rst

    The above command will sort all tags alphabetically, in all rst
    posts.  This command can be run on all posts, to clean up things.

    """

    posts = [post for post in site.timeline if post.source_path in filepaths]

    if len(posts) == 0:
        LOGGER.error("Need at least one post.")

        return

    FMT = 'Tags for {0}:\n{1:>6} - {2}\n{3:>6} - {4}\n'
    OLD = 'old'
    NEW = 'new'

    for post in posts:
        new_tags = sorted(post.tags)

        if dry_run:
            print(FMT.format(
                post.source_path, OLD, post.tags, NEW, new_tags)
            )

        elif new_tags != post.tags:
            _replace_tags_line(post, new_tags)

    return new_tags
开发者ID:LenzGr,项目名称:plugins,代码行数:33,代码来源:tags.py


示例3: _replace_tags_line

def _replace_tags_line(post, tags):
    """ Replaces the line that lists the tags, with given tags. """

    if post.is_two_file:
        path = post.metadata_path
        try:
            if not post.newstylemeta:
                LOGGER.error("{0} uses old-style metadata which is not supported by this plugin, skipping.".format(path))
                return
        except AttributeError:
            # post.newstylemeta is not present in older versions.  If the user
            # has old-style meta files, it will crash or not do the job.
            pass
    else:
        path = post.source_path

    with codecs.open(path, 'r', 'utf-8') as f:
        text = f.readlines()

    tag_identifier = u'.. tags:'
    new_tags = u'.. tags: %s\n' % ', '.join(tags)

    for index, line in enumerate(text[:]):
        if line.startswith(tag_identifier):
            text[index] = new_tags
            break

    with codecs.open(path, 'w+', 'utf-8') as f:
        f.writelines(text)
开发者ID:LenzGr,项目名称:plugins,代码行数:29,代码来源:tags.py


示例4: _replace_tags_line

def _replace_tags_line(post, tags):
    """ Replaces the line that lists the tags, with given tags. """

    source_path = post.source_path

    if post.is_two_file:
        # fixme: currently doesn't handle two post files.
        LOGGER.error(
            "Two file posts are not supported, currently."
            "Skipping %s" % source_path
        )

        return

    with codecs.open(source_path, 'r', 'utf-8') as f:
        post_text = f.readlines()

    tag_identifier = u'.. tags:'
    new_tags = u'.. tags: %s\n' % ', '.join(tags)

    for index, line in enumerate(post_text[:]):
        if line.startswith(tag_identifier):
            post_text[index] = new_tags
            break

    with codecs.open(source_path, 'w+', 'utf-8') as f:
        f.writelines(post_text)
开发者ID:humitos,项目名称:plugins,代码行数:27,代码来源:tags.py


示例5: analyze

 def analyze(self, task, find_sources=False):
     rv = False
     self.whitelist = [re.compile(x) for x in self.site.config['LINK_CHECK_WHITELIST']]
     try:
         filename = task.split(":")[-1]
         d = lxml.html.fromstring(open(filename).read())
         for l in d.iterlinks():
             target = l[0].attrib[l[1]]
             if target == "#":
                 continue
             parsed = urlparse(target)
             if parsed.scheme or target.startswith('//'):
                 continue
             if parsed.fragment:
                 target = target.split('#')[0]
             target_filename = os.path.abspath(
                 os.path.join(os.path.dirname(filename), unquote(target)))
             if any(re.match(x, target_filename) for x in self.whitelist):
                 continue
             elif target_filename not in self.existing_targets:
                 if os.path.exists(target_filename):
                     self.existing_targets.add(target_filename)
                 else:
                     rv = True
                     LOGGER.warn("Broken link in {0}: ".format(filename), target)
                     if find_sources:
                         LOGGER.warn("Possible sources:")
                         LOGGER.warn(os.popen('nikola list --deps ' + task, 'r').read())
                         LOGGER.warn("===============================\n")
     except Exception as exc:
         LOGGER.error("Error with:", filename, exc)
     return rv
开发者ID:emilopez,项目名称:nikola,代码行数:32,代码来源:check.py


示例6: handleMatch

    def handleMatch(self, m):
        gist_id = m.group("gist_id")
        gist_file = m.group("filename")

        gist_elem = etree.Element("div")
        gist_elem.set("class", "gist")
        script_elem = etree.SubElement(gist_elem, "script")

        if requests:
            noscript_elem = etree.SubElement(gist_elem, "noscript")

            try:
                if gist_file:
                    script_elem.set("src", GIST_FILE_JS_URL.format(gist_id, gist_file))
                    raw_gist = self.get_raw_gist_with_filename(gist_id, gist_file)

                else:
                    script_elem.set("src", GIST_JS_URL.format(gist_id))
                    raw_gist = self.get_raw_gist(gist_id)

                # Insert source as <pre/> within <noscript>
                pre_elem = etree.SubElement(noscript_elem, "pre")
                pre_elem.text = AtomicString(raw_gist)

            except GistFetchException as e:
                LOGGER.warn(e.message)
                warning_comment = etree.Comment(" WARNING: {0} ".format(e.message))
                noscript_elem.append(warning_comment)

        else:
            LOGGER.warn('"requests" package not installed.  ' "Please install to add inline gist source.")

        return gist_elem
开发者ID:verbalshadow,项目名称:nikola,代码行数:33,代码来源:mdx_gist.py


示例7: _execute

    def _execute(self, options, args):
        """Start the watcher."""
        try:
            from livereload.server import start
        except ImportError:
            LOGGER.error('To use the auto command, you need to install the '
                         '"livereload" package.')
            return

        # Run an initial build so we are uptodate
        subprocess.call(("nikola", "build"))

        port = options and options.get('port')

        # Create a Guardfile
        with codecs.open("Guardfile", "wb+", "utf8") as guardfile:
            l = ["conf.py", "themes", "templates", self.site.config['GALLERY_PATH']]
            for item in self.site.config['post_pages']:
                l.append(os.path.dirname(item[0]))
            for item in self.site.config['FILES_FOLDERS']:
                l.append(os.path.dirname(item))
            data = GUARDFILE.format(json.dumps(l))
            guardfile.write(data)

        out_folder = self.site.config['OUTPUT_FOLDER']

        os.chmod("Guardfile", 0o755)

        start(port, out_folder, options and options.get('browser'))
开发者ID:emilopez,项目名称:nikola,代码行数:29,代码来源:auto.py


示例8: plain

    def plain(self):
        """Plain Python shell."""
        from nikola import Nikola
        try:
            import conf
            SITE = Nikola(**conf.__dict__)
            SITE.scan_posts()
            gl = {'conf': conf, 'SITE': SITE, 'Nikola': Nikola}
        except ImportError:
            LOGGER.error("No configuration found, cannot run the console.")
        else:
            import code
            try:
                import readline
            except ImportError:
                pass
            else:
                import rlcompleter
                readline.set_completer(rlcompleter.Completer(gl).complete)
                readline.parse_and_bind("tab:complete")

            pythonrc = os.environ.get("PYTHONSTARTUP")
            if pythonrc and os.path.isfile(pythonrc):
                try:
                    execfile(pythonrc)  # NOQA
                except NameError:
                    pass

            code.interact(local=gl, banner=self.header.format('Python'))
开发者ID:emilopez,项目名称:nikola,代码行数:29,代码来源:console.py


示例9: emoji_role

def emoji_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    text = text.lower()
    LOGGER.warn('The role :emoji:`{0}` is deprecated. Use |{0}| instead'.format(text))
    node = nodes.image(
        uri='http://www.tortue.me/emoji/{0}.png'.format(text),
        alt=text,
        classes=['emoji'],
    )
    return [node], []
开发者ID:ChillarAnand,项目名称:plugins,代码行数:9,代码来源:emoji.py


示例10: compile_html

 def compile_html(self, source, dest, is_two_file=True):
     makedirs(os.path.dirname(dest))
     try:
         subprocess.check_call(('pandoc', '-o', dest, source))
     except OSError as e:
         if e.strreror == 'No such file or directory':
             LOGGER.error('To use the pandoc compiler,'
                          ' you have to install the "pandoc" Haskell package.')
             raise Exception('Cannot compile {0} -- pandoc '
                             'missing'.format(source))
开发者ID:emilopez,项目名称:nikola,代码行数:10,代码来源:pandoc.py


示例11: test_gen_tasks

 def test_gen_tasks(self):
     hw = HelloWorld()
     hw.site = MockObject()
     hw.site.config = {}
     for i in hw.gen_tasks():
         self.assertEqual(i['basename'], 'hello_world')
         self.assertEqual(i['uptodate'], [False])
         try:
             self.assertIsInstance(i['actions'][0][1][0], bool)
         except AttributeError:
             LOGGER.warning('Python 2.6 is missing assertIsInstance()')
开发者ID:ifosch,项目名称:plugins,代码行数:11,代码来源:test_helloworld.py


示例12: _execute

 def _execute(self, options, args):
     """Start test server."""
     out_dir = self.site.config['OUTPUT_FOLDER']
     if not os.path.isdir(out_dir):
         LOGGER.error("Missing '{0}' folder?".format(out_dir))
     else:
         os.chdir(out_dir)
         httpd = HTTPServer((options['address'], options['port']),
                            OurHTTPRequestHandler)
         sa = httpd.socket.getsockname()
         LOGGER.notice("Serving HTTP on {0} port {1} ...".format(*sa))
         httpd.serve_forever()
开发者ID:emilopez,项目名称:nikola,代码行数:12,代码来源:serve.py


示例13: ipython

 def ipython(self):
     """IPython shell."""
     from nikola import Nikola
     try:
         import conf
     except ImportError:
         LOGGER.error("No configuration found, cannot run the console.")
     else:
         import IPython
         SITE = Nikola(**conf.__dict__)
         SITE.scan_posts()
         IPython.embed(header=self.header.format('IPython'))
开发者ID:emilopez,项目名称:nikola,代码行数:12,代码来源:console.py


示例14: doc_shortcode

def doc_shortcode(*args, **kwargs):
    """Implement the doc shortcode."""
    text = kwargs['data']
    success, twin_slugs, title, permalink, slug = _doc_link(text, text, LOGGER)
    if success:
        if twin_slugs:
            LOGGER.warn(
                'More than one post with the same slug. Using "{0}" for doc shortcode'.format(permalink))
        return '<a href="{0}">{1}</a>'.format(permalink, title)
    else:
        LOGGER.error(
            '"{0}" slug doesn\'t exist.'.format(slug))
        return '<span class="error text-error" style="color: red;">Invalid link: {0}</span>'.format(text)
开发者ID:FelixSchwarz,项目名称:nikola,代码行数:13,代码来源:doc.py


示例15: bpython

 def bpython(self):
     """bpython shell."""
     from nikola import Nikola
     try:
         import conf
     except ImportError:
         LOGGER.error("No configuration found, cannot run the console.")
     else:
         import bpython
         SITE = Nikola(**conf.__dict__)
         SITE.scan_posts()
         gl = {'conf': conf, 'SITE': SITE, 'Nikola': Nikola}
         bpython.embed(banner=self.header.format('bpython'), locals_=gl)
开发者ID:emilopez,项目名称:nikola,代码行数:13,代码来源:console.py


示例16: tag

    def tag(self, post, count=5):
        """ Return a list of top tags, given a post.

        post: can either be a post object or the source path
        count: the number of tags to return

        """

        if isinstance(post, (bytes_str, unicode_str)):
            source_path = post
            post = self._get_post_from_source_path(source_path)
            if post is None:
                LOGGER.error('No post found for path: %s' % source_path)
                return

        return self._find_top_scoring_tags(post, count)
开发者ID:LenzGr,项目名称:plugins,代码行数:16,代码来源:tags.py


示例17: doc_role

def doc_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    """Handle the doc role."""
    success, twin_slugs, title, permalink, slug = _doc_link(rawtext, text, options, content)
    if success:
        if twin_slugs:
            inliner.reporter.warning(
                'More than one post with the same slug. Using "{0}"'.format(permalink))
            LOGGER.warn(
                'More than one post with the same slug. Using "{0}" for doc role'.format(permalink))
        node = make_link_node(rawtext, title, permalink, options)
        return [node], []
    else:
        msg = inliner.reporter.error(
            '"{0}" slug doesn\'t exist.'.format(slug),
            line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
开发者ID:FelixSchwarz,项目名称:nikola,代码行数:17,代码来源:doc.py


示例18: spell_check

    def spell_check(self, post, lang):
        """ Check spellings for the given post and given language. """

        try:
            dictionary = enchant.request_dict(lang)
            checker = SpellChecker(lang, filters=[EmailFilter, URLFilter])
            checker.set_text(post.text(lang=lang, strip_html=True))
            words = [error.word for error in checker]
            words = [
                word for word in words if not dictionary.check(word)
            ]
            LOGGER.notice(
                'Mis-spelt words in %s: %s' % (
                    post.fragment_deps(lang), ', '.join(words)
                )
            )

        except enchant.DictNotFoundError:
            LOGGER.notice('No dictionary found for %s' % lang)
开发者ID:ChillarAnand,项目名称:punchagan.muse-amuse.in,代码行数:19,代码来源:spell_check.py


示例19: spell_check

    def spell_check(self, post, lang):
        """ Check spellings for the given post and given language. """

        if enchant.dict_exists(lang):
            checker = SpellChecker(lang, filters=[EmailFilter, URLFilter])
            checker.set_text(post.text(lang=lang, strip_html=True))
            words = [error.word for error in checker]
            words = [
                word for word in words if
                self._not_in_other_dictionaries(word, lang)
            ]
            LOGGER.notice(
                'Mis-spelt words in %s: %s' % (
                    post.fragment_deps(lang), ', '.join(words)
                )
            )

        else:
            LOGGER.notice('No dictionary found for %s' % lang)
开发者ID:ChillarAnand,项目名称:plugins,代码行数:19,代码来源:spell_check.py


示例20: _execute

    def _execute(self, options, args):
        """Manage the tags on the site."""

        try:
            import conf

        except ImportError:
            LOGGER.error("No configuration found, cannot run the console.")

        else:
            _reload(conf)
            nikola = Nikola(**conf.__dict__)
            nikola.scan_posts()

            if len(options['add']) > 0 and len(args) > 0:
                add_tags(nikola, options['add'], args, options['dry-run'])

            elif options['list']:
                list_tags(nikola, options['list_sorting'])

            elif options['merge'].count(',') > 0 and len(args) > 0:
                merge_tags(nikola, options['merge'], args, options['dry-run'])

            elif len(options['remove']) > 0 and len(args) > 0:
                remove_tags(nikola, options['remove'], args, options['dry-run'])

            elif len(options['search']) > 0:
                search_tags(nikola, options['search'])

            elif options['tag'] and len(args) > 0:
                tagger = _AutoTag(nikola)
                for post in args:
                    tags = ','.join(tagger.tag(post))
                    add_tags(nikola, tags, [post], options['dry-run'])

            elif options['sort'] and len(args) > 0:
                sort_tags(nikola, args, options['dry-run'])

            else:
                print(self.help())
开发者ID:bronsen,项目名称:plugins,代码行数:40,代码来源:tags.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python testing.assert_raises_regex函数代码示例发布时间:2022-05-27
下一篇:
Python utils.write_metadata函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap