本文整理汇总了Python中nikola.utils.LOGGER类的典型用法代码示例。如果您正苦于以下问题:Python LOGGER类的具体用法?Python LOGGER怎么用?Python LOGGER使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了LOGGER类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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)
示例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)
示例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
示例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
示例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'))
示例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'))
示例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], []
示例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))
示例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()')
示例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()
示例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'))
示例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)
示例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)