Modernize code base to Python 3+ syntax

Replaces syntax that was relevant in earlier Python versions but that
now has modernized equivalents.
This commit is contained in:
Justin Mayer 2020-04-26 09:55:08 +02:00
commit d43b786b30
37 changed files with 104 additions and 171 deletions

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import os
import sys
@ -23,7 +21,7 @@ release = __version__
version = '.'.join(release.split('.')[:1])
last_stable = __version__
rst_prolog = '''
.. |last_stable| replace:: :pelican-doc:`{0}`
.. |last_stable| replace:: :pelican-doc:`{}`
'''.format(last_stable)
# The name of the Pygments (syntax highlighting) style to use.

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import argparse
import logging
import multiprocessing
@ -40,7 +38,7 @@ DEFAULT_CONFIG_NAME = 'pelicanconf.py'
logger = logging.getLogger(__name__)
class Pelican(object):
class Pelican:
def __init__(self, settings):
"""Pelican initialisation
@ -255,7 +253,7 @@ def parse_arguments(argv=None):
parser.add_argument('-s', '--settings', dest='settings',
help='The settings of the application, this is '
'automatically set to {0} if a file exists with this '
'automatically set to {} if a file exists with this '
'name.'.format(DEFAULT_CONFIG_NAME))
parser.add_argument('-d', '--delete-output-directory',
@ -494,11 +492,13 @@ def main(argv=None):
pelican, settings = get_instance(args)
readers = Readers(settings)
reader_descs = sorted(set(['%s (%s)' %
(type(r).__name__,
', '.join(r.file_extensions))
for r in readers.readers.values()
if r.enabled]))
reader_descs = sorted(
{
'%s (%s)' % (type(r).__name__, ', '.join(r.file_extensions))
for r in readers.readers.values()
if r.enabled
}
)
watchers = {'content': folder_watcher(pelican.path,
readers.extensions,

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import hashlib
import logging
import os
@ -10,7 +8,7 @@ from pelican.utils import mkdir_p
logger = logging.getLogger(__name__)
class FileDataCacher(object):
class FileDataCacher:
"""Class that can cache data contained in files"""
def __init__(self, settings, cache_name, caching_policy, load_policy):
@ -33,7 +31,7 @@ class FileDataCacher(object):
try:
with self._cache_open(self._cache_path, 'rb') as fhandle:
self._cache = pickle.load(fhandle)
except (IOError, OSError, UnicodeDecodeError) as err:
except (OSError, UnicodeDecodeError) as err:
logger.debug('Cannot load cache %s (this is normal on first '
'run). Proceeding with empty cache.\n%s',
self._cache_path, err)
@ -67,7 +65,7 @@ class FileDataCacher(object):
mkdir_p(self.settings['CACHE_PATH'])
with self._cache_open(self._cache_path, 'wb') as fhandle:
pickle.dump(self._cache, fhandle)
except (IOError, OSError, pickle.PicklingError) as err:
except (OSError, pickle.PicklingError) as err:
logger.warning('Could not save cache %s\n ... %s',
self._cache_path, err)
@ -116,7 +114,7 @@ class FileStampDataCacher(FileDataCacher):
try:
return self._filestamp_func(filename)
except (IOError, OSError, TypeError) as err:
except (OSError, TypeError) as err:
logger.warning('Cannot get modification stamp for %s\n\t%s',
filename, err)
return ''

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import copy
import datetime
import locale
@ -22,7 +20,7 @@ from pelican.urlwrappers import (Author, Category, Tag, URLWrapper) # NOQA
logger = logging.getLogger(__name__)
class Content(object):
class Content:
"""Represents a content.
:param content: the string to parse, containing the original content.
@ -216,7 +214,7 @@ class Content(object):
def _expand_settings(self, key, klass=None):
if not klass:
klass = self.__class__.__name__
fq_key = ('%s_%s' % (klass, key)).upper()
fq_key = ('{}_{}'.format(klass, key)).upper()
return self.settings[fq_key].format(**self.url_format)
def get_url_setting(self, key):
@ -324,7 +322,7 @@ class Content(object):
(?:href|src|poster|data|cite|formaction|action)\s*=\s*)
(?P<quote>["\']) # require value to be quoted
(?P<path>{0}(?P<value>.*?)) # the url value
(?P<path>{}(?P<value>.*?)) # the url value
\2""".format(intrasite_link_regex)
return re.compile(regex, re.X)

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import calendar
import errno
import fnmatch
@ -28,7 +26,7 @@ class PelicanTemplateNotFound(Exception):
pass
class Generator(object):
class Generator:
"""Baseclass generator"""
def __init__(self, context, settings, path, theme, output_path,
@ -262,7 +260,7 @@ class _FileLoader(BaseLoader):
if template != self.path or not os.path.exists(self.fullpath):
raise TemplateNotFound(template)
mtime = os.path.getmtime(self.fullpath)
with open(self.fullpath, 'r', encoding='utf-8') as f:
with open(self.fullpath, encoding='utf-8') as f:
source = f.read()
return (source, self.fullpath,
lambda: mtime == os.path.getmtime(self.fullpath))

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import logging
import os
import sys

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import functools
import logging
import os
@ -13,7 +11,7 @@ PaginationRule = namedtuple(
)
class Paginator(object):
class Paginator:
def __init__(self, name, url, object_list, settings, per_page=None):
self.name = name
self.url = url
@ -61,7 +59,7 @@ class Paginator(object):
page_range = property(_get_page_range)
class Page(object):
class Page:
def __init__(self, name, url, object_list, number, paginator, settings):
self.full_name = name
self.name, self.extension = os.path.splitext(name)
@ -74,7 +72,7 @@ class Page(object):
self.settings = settings
def __repr__(self):
return '<Page %s of %s>' % (self.number, self.paginator.num_pages)
return '<Page {} of {}>'.format(self.number, self.paginator.num_pages)
def has_next(self):
return self.number < self.paginator.num_pages

View file

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from blinker import signal
# Run-level signals:

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import datetime
import logging
import os
@ -101,7 +99,7 @@ def _filter_discardable_metadata(metadata):
return {name: val for name, val in metadata.items() if val is not _DISCARD}
class BaseReader(object):
class BaseReader:
"""Base class to read files.
This class is used to process static files, and it can be inherited for

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import re
from docutils import nodes, utils

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import argparse
import logging
import os

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import copy
import importlib.util
import inspect

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log"
SITEURL = 'http://blog.notmyidea.org'

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale
import logging
import os
@ -134,7 +132,7 @@ def skipIfNoExecutable(executable):
res = None
if res is None:
return unittest.skip('{0} executable not found'.format(executable))
return unittest.skip('{} executable not found'.format(executable))
return lambda func: func

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import os
from shutil import rmtree
from tempfile import mkdtemp

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import datetime
import locale
import logging
@ -27,7 +25,7 @@ class TestBase(LoggedTestCase):
def setUp(self):
super().setUp()
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
self.page_kwargs = {
'content': TEST_CONTENT,
'context': {
@ -56,13 +54,13 @@ class TestBase(LoggedTestCase):
def _copy_page_kwargs(self):
# make a deep copy of page_kwargs
page_kwargs = dict([(key, self.page_kwargs[key]) for key in
self.page_kwargs])
page_kwargs = {key: self.page_kwargs[key] for key in self.page_kwargs}
for key in page_kwargs:
if not isinstance(page_kwargs[key], dict):
break
page_kwargs[key] = dict([(subkey, page_kwargs[key][subkey])
for subkey in page_kwargs[key]])
page_kwargs[key] = {
subkey: page_kwargs[key][subkey] for subkey in page_kwargs[key]
}
return page_kwargs

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale
import os
from shutil import copy, rmtree
@ -27,7 +25,7 @@ CONTENT_DIR = os.path.join(CUR_DIR, 'content')
class TestGenerator(unittest.TestCase):
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
self.settings = get_settings()
self.settings['READERS'] = {'asc': None}
self.generator = Generator(self.settings.copy(), self.settings,
@ -403,7 +401,7 @@ class TestArticlesGenerator(unittest.TestCase):
'period' : a tuple of year, month, day according to the time period
"""
old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
settings = get_settings()
settings['YEAR_ARCHIVE_SAVE_AS'] = 'posts/{date:%Y}/index.html'
@ -788,7 +786,7 @@ class TestTemplatePagesGenerator(unittest.TestCase):
self.temp_content = mkdtemp(prefix='pelicantests.')
self.temp_output = mkdtemp(prefix='pelicantests.')
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self):
rmtree(self.temp_content)
@ -823,7 +821,7 @@ class TestTemplatePagesGenerator(unittest.TestCase):
self.assertTrue(os.path.exists(output_path))
# output content is correct
with open(output_path, 'r') as output_file:
with open(output_path) as output_file:
self.assertEqual(output_file.read(), 'foo: bar')
@ -1013,7 +1011,7 @@ class TestStaticGenerator(unittest.TestCase):
f.write("staticcontent")
self.generator.generate_context()
self.generator.generate_output(None)
with open(self.endfile, "r") as f:
with open(self.endfile) as f:
self.assertEqual(f.read(), "staticcontent")
@unittest.skipUnless(MagicMock, 'Needs Mock module')
@ -1162,7 +1160,7 @@ class TestJinja2Environment(unittest.TestCase):
self.temp_content = mkdtemp(prefix='pelicantests.')
self.temp_output = mkdtemp(prefix='pelicantests.')
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self):
rmtree(self.temp_content)
@ -1197,7 +1195,7 @@ class TestJinja2Environment(unittest.TestCase):
self.assertTrue(os.path.exists(output_path))
# output content is correct
with open(output_path, 'r') as output_file:
with open(output_path) as output_file:
self.assertEqual(output_file.read(), expected)
def test_jinja2_filter(self):

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale
import os
import re
@ -41,7 +39,7 @@ class TestBloggerXmlImporter(unittest.TestCase):
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
self.posts = blogger2fields(BLOGGER_XML_SAMPLE)
def tearDown(self):
@ -90,7 +88,7 @@ class TestWordpressXmlImporter(unittest.TestCase):
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
self.posts = wp2fields(WORDPRESS_XML_SAMPLE)
self.custposts = wp2fields(WORDPRESS_XML_SAMPLE, True)
@ -282,9 +280,9 @@ class TestWordpressXmlImporter(unittest.TestCase):
def test_decode_wp_content(self):
""" Check that we can decode a wordpress content string."""
with open(WORDPRESS_ENCODED_CONTENT_SAMPLE, 'r') as encoded_file:
with open(WORDPRESS_ENCODED_CONTENT_SAMPLE) as encoded_file:
encoded_content = encoded_file.read()
with open(WORDPRESS_DECODED_CONTENT_SAMPLE, 'r') as decoded_file:
with open(WORDPRESS_DECODED_CONTENT_SAMPLE) as decoded_file:
decoded_content = decoded_file.read()
self.assertEqual(
decode_wp_content(encoded_content, br=False),
@ -405,7 +403,7 @@ class TestBuildHeader(unittest.TestCase):
class TestWordpressXMLAttachements(unittest.TestCase):
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
self.attachments = get_attachments(WORDPRESS_XML_SAMPLE)
def tearDown(self):

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale
from jinja2.utils import generate_lorem_ipsum
@ -19,7 +17,7 @@ class TestPage(unittest.TestCase):
def setUp(self):
super().setUp()
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
self.page_kwargs = {
'content': TEST_CONTENT,
'context': {

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale
import logging
import os
@ -47,7 +45,7 @@ class TestPelican(LoggedTestCase):
self.temp_cache = mkdtemp(prefix='pelican_cache.')
self.maxDiff = None
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self):
read_settings() # cleanup PYGMENTS_RST_OPTIONS
@ -60,7 +58,7 @@ class TestPelican(LoggedTestCase):
out, err = subprocess.Popen(
['git', 'diff', '--no-ext-diff', '--exit-code',
'-w', left_path, right_path],
env={str('PAGER'): str('')},
env={'PAGER': ''},
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()
@ -131,9 +129,9 @@ class TestPelican(LoggedTestCase):
def test_custom_locale_generation_works(self):
'''Test that generation with fr_FR.UTF-8 locale works'''
if sys.platform == 'win32':
our_locale = str('French')
our_locale = 'French'
else:
our_locale = str('fr_FR.UTF-8')
our_locale = 'fr_FR.UTF-8'
settings = read_settings(path=SAMPLE_FR_CONFIG, override={
'PATH': INPUT_PATH,

View file

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import os
from contextlib import contextmanager
@ -84,9 +81,9 @@ class PluginTest(unittest.TestCase):
def test_load_plugins(self):
def get_plugin_names(plugins):
return set(
return {
plugin.NAME if hasattr(plugin, 'NAME') else plugin.__name__
for plugin in plugins)
for plugin in plugins}
# existing namespace plugins
existing_ns_plugins = load_plugins({})

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import os
from pelican import readers
@ -92,9 +90,9 @@ class DefaultReaderTest(ReaderTest):
for tag in content:
readers.find_empty_alt(tag, '/test/path')
log_mock.warning.assert_called_with(
u'Empty alt attribute for image %s in %s',
u'test-image.png',
u'/test/path',
'Empty alt attribute for image %s in %s',
'test-image.png',
'/test/path',
extra={'limit_msg':
'Other images have empty alt attributes'}
)

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from pelican.tests.support import unittest
try:

View file

@ -7,12 +7,12 @@ from pelican.server import ComplexHTTPRequestHandler
from pelican.tests.support import unittest
class MockRequest(object):
class MockRequest:
def makefile(self, *args, **kwargs):
return BytesIO(b"")
class MockServer(object):
class MockServer:
pass

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import copy
import locale
import os
@ -21,7 +19,7 @@ class TestSettingsConfiguration(unittest.TestCase):
"""
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
self.PATH = abspath(dirname(__file__))
default_conf = join(self.PATH, 'default_conf.py')
self.settings = read_settings(default_conf)
@ -143,7 +141,7 @@ class TestSettingsConfiguration(unittest.TestCase):
# Test that the default locale is set if not specified in settings
# Reset locale to Python's default locale
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
self.assertEqual(self.settings['LOCALE'], DEFAULT_CONFIG['LOCALE'])
configure_settings(self.settings)

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import warnings
from pelican.tests.support import unittest

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from pelican.tests.support import unittest
from pelican.urlwrappers import Author, Category, Tag, URLWrapper
@ -40,7 +38,7 @@ class TestURLWrapper(unittest.TestCase):
self.assertNotEqual(tag, author)
# should be equal vs text representing the same name
self.assertEqual(tag, u'test')
self.assertEqual(tag, 'test')
# should not be equal vs binary
self.assertNotEqual(tag, b'test')
@ -54,7 +52,7 @@ class TestURLWrapper(unittest.TestCase):
self.assertEqual(author, author_equal)
cat_ascii = Category('指導書', settings={})
self.assertEqual(cat_ascii, u'zhi dao shu')
self.assertEqual(cat_ascii, 'zhi dao shu')
def test_slugify_with_substitutions_and_dots(self):
tag = Tag('Tag Dot', settings={'TAG_REGEX_SUBSTITUTIONS': [

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale
import logging
import os
@ -480,9 +478,9 @@ class TestUtils(LoggedTestCase):
old_locale = locale.setlocale(locale.LC_ALL)
if platform == 'win32':
locale.setlocale(locale.LC_ALL, str('Turkish'))
locale.setlocale(locale.LC_ALL, 'Turkish')
else:
locale.setlocale(locale.LC_ALL, str('tr_TR.UTF-8'))
locale.setlocale(locale.LC_ALL, 'tr_TR.UTF-8')
d = utils.SafeDatetime(2012, 8, 29)
@ -514,9 +512,9 @@ class TestUtils(LoggedTestCase):
old_locale = locale.setlocale(locale.LC_ALL)
if platform == 'win32':
locale.setlocale(locale.LC_ALL, str('French'))
locale.setlocale(locale.LC_ALL, 'French')
else:
locale.setlocale(locale.LC_ALL, str('fr_FR.UTF-8'))
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
d = utils.SafeDatetime(2012, 8, 29)
@ -557,7 +555,7 @@ class TestCopy(unittest.TestCase):
def setUp(self):
self.root_dir = mkdtemp(prefix='pelicantests.')
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self):
shutil.rmtree(self.root_dir)
@ -666,26 +664,26 @@ class TestDateFormatter(unittest.TestCase):
# This test tries to reproduce an issue that
# occurred with python3.3 under macos10 only
if platform == 'win32':
locale.setlocale(locale.LC_ALL, str('French'))
locale.setlocale(locale.LC_ALL, 'French')
else:
locale.setlocale(locale.LC_ALL, str('fr_FR.UTF-8'))
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
date = utils.SafeDatetime(2014, 8, 14)
# we compare the lower() dates since macos10 returns
# "Jeudi" for %A whereas linux reports "jeudi"
self.assertEqual(
u'jeudi, 14 août 2014',
'jeudi, 14 août 2014',
utils.strftime(date, date_format="%A, %d %B %Y").lower())
df = utils.DateFormatter()
self.assertEqual(
u'jeudi, 14 août 2014',
'jeudi, 14 août 2014',
df(date, date_format="%A, %d %B %Y").lower())
# Let us now set the global locale to C:
locale.setlocale(locale.LC_ALL, str('C'))
locale.setlocale(locale.LC_ALL, 'C')
# DateFormatter should still work as expected
# since it is the whole point of DateFormatter
# (This is where pre-2014/4/15 code fails on macos10)
df_date = df(date, date_format="%A, %d %B %Y").lower()
self.assertEqual(u'jeudi, 14 août 2014', df_date)
self.assertEqual('jeudi, 14 août 2014', df_date)
@unittest.skipUnless(locale_available('fr_FR.UTF-8') or
locale_available('French'),

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
@ -40,7 +39,7 @@ def decode_wp_content(content, br=True):
if start == -1:
content = content + pre_part
continue
name = "<pre wp-pre-tag-{0}></pre>".format(pre_index)
name = "<pre wp-pre-tag-{}></pre>".format(pre_index)
pre_tags[name] = pre_part[start:] + "</pre>"
content = content + pre_part[0:start] + name
pre_index += 1
@ -154,7 +153,7 @@ def wp2fields(xml, wp_custpost=False):
content = item.find('encoded').string
raw_date = item.find('post_date').string
if raw_date == u'0000-00-00 00:00:00':
if raw_date == '0000-00-00 00:00:00':
date = None
else:
date_object = SafeDatetime.strptime(
@ -258,7 +257,7 @@ def dc2fields(file):
category_list = {}
posts = []
with open(file, 'r', encoding='utf-8') as f:
with open(file, encoding='utf-8') as f:
for line in f:
# remove final \n
@ -394,7 +393,7 @@ def posterous2fields(api_token, email, password):
def get_posterous_posts(api_token, email, password, page=1):
base64string = base64.encodestring(
("%s:%s" % (email, password)).encode('utf-8')).replace('\n', '')
("{}:{}".format(email, password)).encode('utf-8')).replace('\n', '')
url = ("http://posterous.com/api/v2/users/me/sites/primary/"
"posts?api_token=%s&page=%d") % (api_token, page)
request = urllib_request.Request(url)
@ -553,7 +552,7 @@ def build_header(title, date, author, categories, tags, slug,
from docutils.utils import column_width
header = '%s\n%s\n' % (title, '#' * column_width(title))
header = '{}\n{}\n'.format(title, '#' * column_width(title))
if date:
header += ':date: %s\n' % date
if author:
@ -738,7 +737,7 @@ def download_attachments(output_path, urls):
try:
urlretrieve(url, os.path.join(full_path, filename))
locations[url] = os.path.join(localpath, filename)
except (URLError, IOError) as e:
except (URLError, OSError) as e:
# Python 2.7 throws an IOError rather Than URLError
logger.warning("No file could be downloaded from %s\n%s", url, e)
return locations
@ -828,7 +827,7 @@ def fields2pelican(
new_content = decode_wp_content(content)
else:
paragraphs = content.splitlines()
paragraphs = ['<p>{0}</p>'.format(p) for p in paragraphs]
paragraphs = ['<p>{}</p>'.format(p) for p in paragraphs]
new_content = ''.join(paragraphs)
fp.write(new_content)
@ -862,7 +861,7 @@ def fields2pelican(
os.remove(html_filename)
with open(out_filename, 'r', encoding='utf-8') as fs:
with open(out_filename, encoding='utf-8') as fs:
content = fs.read()
if out_markup == 'markdown':
# In markdown, to insert a <br />, end a line with two

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import locale
@ -87,9 +86,9 @@ def ask(question, answer=str, default=None, length=None):
r = ''
while True:
if default:
r = input('> {0} [{1}] '.format(question, default))
r = input('> {} [{}] '.format(question, default))
else:
r = input('> {0} '.format(question, default))
r = input('> {} '.format(question, default))
r = r.strip()
@ -101,7 +100,7 @@ def ask(question, answer=str, default=None, length=None):
print('You must enter something')
else:
if length and len(r) != length:
print('Entry must be {0} characters long'.format(length))
print('Entry must be {} characters long'.format(length))
else:
break
@ -111,11 +110,11 @@ def ask(question, answer=str, default=None, length=None):
r = None
while True:
if default is True:
r = input('> {0} (Y/n) '.format(question))
r = input('> {} (Y/n) '.format(question))
elif default is False:
r = input('> {0} (y/N) '.format(question))
r = input('> {} (y/N) '.format(question))
else:
r = input('> {0} (y/n) '.format(question))
r = input('> {} (y/n) '.format(question))
r = r.strip().lower()
@ -135,9 +134,9 @@ def ask(question, answer=str, default=None, length=None):
r = None
while True:
if default:
r = input('> {0} [{1}] '.format(question, default))
r = input('> {} [{}] '.format(question, default))
else:
r = input('> {0} '.format(question))
r = input('> {} '.format(question))
r = r.strip()
@ -167,7 +166,7 @@ def ask_timezone(question, default, tzurl):
break
else:
print('Please enter a valid time zone:\n'
' (check [{0}])'.format(tzurl))
' (check [{}])'.format(tzurl))
return r
@ -199,7 +198,7 @@ needed by Pelican.
os.environ.get('VIRTUAL_ENV', os.curdir), '.project')
no_path_was_specified = hasattr(args.path, 'is_default_path')
if os.path.isfile(project) and no_path_was_specified:
CONF['basedir'] = open(project, 'r').read().rstrip("\n")
CONF['basedir'] = open(project).read().rstrip("\n")
print('Using project associated with current virtual environment. '
'Will save to:\n%s\n' % CONF['basedir'])
else:
@ -300,12 +299,12 @@ needed by Pelican.
try:
os.makedirs(os.path.join(CONF['basedir'], 'content'))
except OSError as e:
print('Error: {0}'.format(e))
print('Error: {}'.format(e))
try:
os.makedirs(os.path.join(CONF['basedir'], 'output'))
except OSError as e:
print('Error: {0}'.format(e))
print('Error: {}'.format(e))
try:
with open(os.path.join(CONF['basedir'], 'pelicanconf.py'),
@ -318,7 +317,7 @@ needed by Pelican.
fd.write(_template.render(**conf_python))
fd.close()
except OSError as e:
print('Error: {0}'.format(e))
print('Error: {}'.format(e))
try:
with open(os.path.join(CONF['basedir'], 'publishconf.py'),
@ -327,7 +326,7 @@ needed by Pelican.
fd.write(_template.render(**CONF))
fd.close()
except OSError as e:
print('Error: {0}'.format(e))
print('Error: {}'.format(e))
if automation:
try:
@ -337,7 +336,7 @@ needed by Pelican.
fd.write(_template.render(**CONF))
fd.close()
except OSError as e:
print('Error: {0}'.format(e))
print('Error: {}'.format(e))
try:
with open(os.path.join(CONF['basedir'], 'Makefile'),
'w', encoding='utf-8') as fd:
@ -346,7 +345,7 @@ needed by Pelican.
fd.write(_template.render(py_v=py_v, **CONF))
fd.close()
except OSError as e:
print('Error: {0}'.format(e))
print('Error: {}'.format(e))
print('Done. Your new project is available at %s' % CONF['basedir'])

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import os
@ -11,7 +10,7 @@ def err(msg, die=None):
"""Print an error message and exits if an exit code is given"""
sys.stderr.write(msg + '\n')
if die:
sys.exit((die if type(die) is int else 1))
sys.exit(die if type(die) is int else 1)
try:
@ -49,7 +48,7 @@ def main():
help="Show the themes path and exit")
excl.add_argument(
'-V', '--version', action='version',
version='pelican-themes v{0}'.format(__version__),
version='pelican-themes v{}'.format(__version__),
help='Print the version of this script')
parser.add_argument(
@ -249,12 +248,12 @@ def clean(v=False):
if os.path.islink(path):
if is_broken_link(path):
if v:
print('Removing {0}'.format(path))
print('Removing {}'.format(path))
try:
os.remove(path)
except OSError:
print('Error: cannot remove {0}'.format(path))
print('Error: cannot remove {}'.format(path))
else:
c += 1
print("\nRemoved {0} broken links".format(c))
print("\nRemoved {} broken links".format(c))

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import functools
import logging
import os
@ -10,7 +8,7 @@ logger = logging.getLogger(__name__)
@functools.total_ordering
class URLWrapper(object):
class URLWrapper:
def __init__(self, name, settings):
self.settings = settings
self._name = name
@ -110,7 +108,7 @@ class URLWrapper(object):
"cat/{slug}" Useful for pagination.
"""
setting = "%s_%s" % (self.__class__.__name__.upper(), key)
setting = "{}_{}".format(self.__class__.__name__.upper(), key)
value = self.settings[setting]
if not isinstance(value, str):
logger.warning('%s is set to %s', setting, value)

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import datetime
import fnmatch
import locale
@ -99,7 +97,7 @@ class SafeDatetime(datetime.datetime):
return super().strftime(fmt)
class DateFormatter(object):
class DateFormatter:
'''A date formatter object used as a jinja filter
Uses the `strftime` implementation and makes sure jinja uses the locale
@ -125,7 +123,7 @@ class DateFormatter(object):
return formatted
class memoized(object):
class memoized:
"""Function decorator to cache return values.
If called later with the same arguments, the cached value is returned
@ -209,7 +207,7 @@ def get_date(string):
try:
return dateutil.parser.parse(string, default=default)
except (TypeError, ValueError):
raise ValueError('{0!r} is not a valid date'.format(string))
raise ValueError('{!r} is not a valid date'.format(string))
@contextmanager
@ -646,7 +644,7 @@ def get_original_items(items, with_str):
def _warn_source_paths(msg, items, *extra):
args = [len(items)]
args.extend(extra)
args.extend((x.source_path for x in items))
args.extend(x.source_path for x in items)
logger.warning('{}: {}'.format(msg, '\n%s' * len(items)), *args)
# warn if several items have the same lang

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import logging
import os
from urllib.parse import urljoin
@ -16,7 +14,7 @@ from pelican.utils import (get_relative_path, is_selected_for_writing,
logger = logging.getLogger(__name__)
class Writer(object):
class Writer:
def __init__(self, output_path, settings=None):
self.output_path = output_path

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log"
SITESUBTITLE = 'A personal blog.'

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log"
SITEURL = 'http://blog.notmyidea.org'

View file

@ -1,6 +1,5 @@
#!/usr/bin/env python
from io import open
from os import walk
from os.path import join, relpath