mirror of
https://github.com/gryf/ebook-converter.git
synced 2026-03-07 18:15:46 +01:00
Removed prints and extract function from init module
This commit is contained in:
@@ -5,13 +5,11 @@ meaning as possible.
|
||||
import errno
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from math import ceil
|
||||
|
||||
from ebook_converter import force_unicode, prints, sanitize_file_name
|
||||
from ebook_converter.constants_old import (
|
||||
filesystem_encoding, plugins, preferred_encoding, isosx
|
||||
)
|
||||
from ebook_converter import force_unicode, sanitize_file_name
|
||||
from ebook_converter.constants_old import (filesystem_encoding,
|
||||
preferred_encoding)
|
||||
from ebook_converter.utils.localization import get_udc
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import os
|
||||
from collections import defaultdict
|
||||
from threading import Thread
|
||||
|
||||
from ebook_converter import walk, prints
|
||||
from ebook_converter import walk
|
||||
from ebook_converter.constants_old import isosx
|
||||
from ebook_converter.constants_old import plugins, DEBUG
|
||||
from ebook_converter.constants_old import filesystem_encoding
|
||||
@@ -67,7 +67,7 @@ def fc_list():
|
||||
try:
|
||||
ans.append(d.decode(filesystem_encoding))
|
||||
except ValueError:
|
||||
prints('Ignoring undecodeable font path: %r' % d)
|
||||
print(f'Ignoring undecodeable font path: {d}')
|
||||
continue
|
||||
end(str_list)
|
||||
if len(ans) < 3:
|
||||
@@ -309,7 +309,7 @@ class FontScanner(Thread):
|
||||
files = tuple(walk(folder))
|
||||
except EnvironmentError as e:
|
||||
if DEBUG:
|
||||
prints('Failed to walk font folder:', folder, str(e))
|
||||
print(f'Failed to walk font folder: {folder}, {e}')
|
||||
continue
|
||||
for candidate in files:
|
||||
if (candidate.rpartition('.')[-1].lower() not in
|
||||
@@ -332,8 +332,8 @@ class FontScanner(Thread):
|
||||
self.read_font_metadata(candidate, fileid)
|
||||
except Exception as e:
|
||||
if DEBUG:
|
||||
prints('Failed to read metadata from font file:',
|
||||
candidate, str(e))
|
||||
print(f'Failed to read metadata from font file '
|
||||
f'{candidate}: {e}')
|
||||
continue
|
||||
|
||||
if frozenset(cached_fonts) != frozenset(self.cached_fonts):
|
||||
@@ -369,18 +369,18 @@ class FontScanner(Thread):
|
||||
def dump_fonts(self):
|
||||
self.join()
|
||||
for family in self.font_families:
|
||||
prints(family)
|
||||
print(family)
|
||||
for font in self.fonts_for_family(family):
|
||||
prints('\t%s: %s' % (font['full_name'], font['path']))
|
||||
prints(end='\t')
|
||||
print('\t%s: %s' % (font['full_name'], font['path']))
|
||||
print(end='\t')
|
||||
for key in ('font-stretch', 'font-weight', 'font-style'):
|
||||
prints('%s: %s' % (key, font[key]), end=' ')
|
||||
prints()
|
||||
prints('\tSub-family:', font['wws_subfamily_name'] or
|
||||
font['preferred_subfamily_name'] or
|
||||
font['subfamily_name'])
|
||||
prints()
|
||||
prints()
|
||||
print('%s: %s' % (key, font[key]))
|
||||
print()
|
||||
print('\tSub-family: %s' % (font['wws_subfamily_name'] or
|
||||
font['preferred_subfamily_name']
|
||||
or font['subfamily_name']))
|
||||
print()
|
||||
print()
|
||||
|
||||
|
||||
font_scanner = FontScanner()
|
||||
|
||||
@@ -204,15 +204,13 @@ def option_parser():
|
||||
|
||||
|
||||
def print_stats(old_stats, new_stats):
|
||||
from ebook_converter import prints
|
||||
prints('========= Table comparison (original vs. subset) =========')
|
||||
prints('Table', ' ', '%10s'%'Size', ' ', 'Percent', ' ', '%10s'%'New Size',
|
||||
' New Percent')
|
||||
prints('='*80)
|
||||
print('========= Table comparison (original vs. subset) =========')
|
||||
print('Table Size Percent New Size New Percent')
|
||||
print('='*80)
|
||||
old_total = sum(old_stats.values())
|
||||
new_total = sum(new_stats.values())
|
||||
tables = sorted(old_stats, key=lambda x:old_stats[x],
|
||||
reverse=True)
|
||||
tables = sorted(old_stats, key=lambda x: old_stats[x],
|
||||
reverse=True)
|
||||
for table in tables:
|
||||
osz = old_stats[table]
|
||||
op = osz/old_total * 100
|
||||
@@ -220,15 +218,14 @@ def print_stats(old_stats, new_stats):
|
||||
np = nsz/new_total * 100
|
||||
suffix = ' | same size'
|
||||
if nsz != osz:
|
||||
suffix = ' | reduced to %.1f %%'%(nsz/osz * 100)
|
||||
prints('%4s'%table, ' ', '%10s'%osz, ' ', '%5.1f %%'%op, ' ',
|
||||
'%10s'%nsz, ' ', '%5.1f %%'%np, suffix)
|
||||
prints('='*80)
|
||||
suffix = ' | reduced to %.1f %%' % (nsz/osz * 100)
|
||||
print('%4s %10s %5.1f %% %10s %5.1f %% %s' %
|
||||
(table, osz, op, nsz, np, suffix))
|
||||
print('='*80)
|
||||
|
||||
|
||||
def main(args):
|
||||
import sys, time
|
||||
from ebook_converter import prints
|
||||
parser = option_parser()
|
||||
opts, args = parser.parse_args(args)
|
||||
if len(args) < 4 or len(args) > 4:
|
||||
@@ -243,7 +240,7 @@ def main(args):
|
||||
|
||||
def not_single(c):
|
||||
if len(c) > 1:
|
||||
prints(c, 'is not a single character', file=sys.stderr)
|
||||
print(f'{c}is not a single character')
|
||||
raise SystemExit(1)
|
||||
|
||||
def conv_code(c):
|
||||
@@ -255,7 +252,7 @@ def main(args):
|
||||
if '-' in c:
|
||||
parts = [x.strip() for x in c.split('-')]
|
||||
if len(parts) != 2:
|
||||
prints('Invalid range:', c, file=sys.stderr)
|
||||
print(f'Invalid range: {c}')
|
||||
raise SystemExit(1)
|
||||
if opts.codes:
|
||||
parts = tuple(map(conv_code, parts))
|
||||
@@ -272,13 +269,14 @@ def main(args):
|
||||
reduced = (len(sf)/len(orig)) * 100
|
||||
|
||||
def sz(x):
|
||||
return '%gKB'%(len(x)/1024.)
|
||||
return '%gKB' % (len(x)/1024.)
|
||||
print_stats(old_stats, new_stats)
|
||||
prints('Original size:', sz(orig), 'Subset size:', sz(sf), 'Reduced to: %g%%'%(reduced))
|
||||
prints('Subsetting took %g seconds'%taken)
|
||||
print('Original size:', sz(orig), 'Subset size:', sz(sf),
|
||||
'Reduced to: %g%%' % (reduced))
|
||||
print('Subsetting took %g seconds' % taken)
|
||||
with open(off, 'wb') as f:
|
||||
f.write(sf)
|
||||
prints('Subset font written to:', off)
|
||||
print('Subset font written to:', off)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -5,7 +5,6 @@ Created on 23 Sep 2010
|
||||
"""
|
||||
import re, string, traceback, numbers
|
||||
|
||||
from ebook_converter import prints
|
||||
from ebook_converter.constants_old import DEBUG
|
||||
from ebook_converter.utils.formatter_functions import formatter_functions
|
||||
|
||||
@@ -373,7 +372,7 @@ class TemplateFormatter(string.Formatter):
|
||||
if DEBUG: # and getattr(e, 'is_locking_error', False):
|
||||
traceback.print_exc()
|
||||
if column_name:
|
||||
prints('Error evaluating column named:', column_name)
|
||||
print('Error evaluating column named: {column_name}')
|
||||
ans = error_value + ' ' + str(e)
|
||||
return ans
|
||||
|
||||
|
||||
@@ -4,10 +4,10 @@ A simplified logging system
|
||||
import sys
|
||||
import traceback
|
||||
import io
|
||||
import os
|
||||
from functools import partial
|
||||
from threading import Lock
|
||||
|
||||
from ebook_converter import force_unicode, prints
|
||||
from ebook_converter import constants_old
|
||||
|
||||
|
||||
DEBUG = 0
|
||||
@@ -22,13 +22,13 @@ class Stream(object):
|
||||
if stream is None:
|
||||
stream = io.BytesIO()
|
||||
self.stream = getattr(stream, 'buffer', stream)
|
||||
self._prints = partial(prints, safe_encode=True, file=stream)
|
||||
# self._prints = partial(prints, safe_encode=True, file=stream)
|
||||
|
||||
def flush(self):
|
||||
self.stream.flush()
|
||||
|
||||
def prints(self, level, *args, **kwargs):
|
||||
self._prints(*args, **kwargs)
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class ANSIStream(Stream):
|
||||
@@ -43,97 +43,34 @@ class ANSIStream(Stream):
|
||||
}
|
||||
|
||||
def prints(self, level, *args, **kwargs):
|
||||
from ebook_converter.utils.terminal import ColoredStream
|
||||
with ColoredStream(self.stream, self.color[level]):
|
||||
self._prints(*args, **kwargs)
|
||||
|
||||
def flush(self):
|
||||
self.stream.flush()
|
||||
|
||||
|
||||
class FileStream(Stream):
|
||||
|
||||
def __init__(self, stream=None):
|
||||
Stream.__init__(self, stream)
|
||||
|
||||
def prints(self, level, *args, **kwargs):
|
||||
self._prints(*args, **kwargs)
|
||||
|
||||
|
||||
class HTMLStream(Stream):
|
||||
|
||||
color = {DEBUG: b'<span style="color:green">',
|
||||
INFO: b'<span>',
|
||||
WARN: b'<span style="color:blue">',
|
||||
ERROR: b'<span style="color:red">'}
|
||||
normal = b'</span>'
|
||||
|
||||
def __init__(self, stream=sys.stdout):
|
||||
Stream.__init__(self, stream)
|
||||
|
||||
def prints(self, level, *args, **kwargs):
|
||||
self.stream.write(self.color[level])
|
||||
kwargs['file'] = self.stream
|
||||
self._prints(*args, **kwargs)
|
||||
self.stream.write(self.normal)
|
||||
|
||||
def flush(self):
|
||||
self.stream.flush()
|
||||
|
||||
|
||||
class UnicodeHTMLStream(HTMLStream):
|
||||
|
||||
color = {k: v.decode('ascii') for k, v in HTMLStream.color.items()}
|
||||
normal = HTMLStream.normal.decode('ascii')
|
||||
|
||||
def __init__(self):
|
||||
self.clear()
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
def prints(self, level, *args, **kwargs):
|
||||
col = self.color[level]
|
||||
if col != self.last_col:
|
||||
if self.data:
|
||||
self.data.append(self.normal)
|
||||
self.data.append(col)
|
||||
self.last_col = col
|
||||
|
||||
fobj = kwargs.get('file', sys.stdout)
|
||||
sep = kwargs.get('sep', ' ')
|
||||
enc = ('utf-8' if os.getenv('CALIBRE_WORKER')
|
||||
else constants_old.preferred_encoding)
|
||||
if isinstance(sep, bytes):
|
||||
sep = sep.decode(enc)
|
||||
end = kwargs.get('end', '\n')
|
||||
|
||||
for arg in args:
|
||||
if isinstance(end, bytes):
|
||||
end = end.decode(enc)
|
||||
count = 0
|
||||
for i, arg in enumerate(args):
|
||||
if isinstance(arg, bytes):
|
||||
arg = force_unicode(arg)
|
||||
elif not isinstance(arg, str):
|
||||
arg = str(arg)
|
||||
self.data.append(arg+sep)
|
||||
self.plain_text.append(arg+sep)
|
||||
self.data.append(end)
|
||||
self.plain_text.append(end)
|
||||
arg = arg.decode(enc)
|
||||
arg = repr(arg)
|
||||
try:
|
||||
fobj.write(arg)
|
||||
count += len(arg)
|
||||
except Exception:
|
||||
arg = repr(arg)
|
||||
fobj.write(arg)
|
||||
count += len(arg)
|
||||
if i != len(args)-1:
|
||||
fobj.write(sep)
|
||||
count += len(sep)
|
||||
count += len(end)
|
||||
|
||||
def clear(self):
|
||||
self.data = []
|
||||
self.plain_text = []
|
||||
self.last_col = self.color[INFO]
|
||||
|
||||
@property
|
||||
def html(self):
|
||||
end = self.normal if self.data else ''
|
||||
return ''.join(self.data) + end
|
||||
|
||||
def dump(self):
|
||||
return [self.data, self.plain_text, self.last_col]
|
||||
|
||||
def load(self, dump):
|
||||
self.data, self.plain_text, self.last_col = dump
|
||||
|
||||
def append_dump(self, dump):
|
||||
d, p, lc = dump
|
||||
self.data.extend(d)
|
||||
self.plain_text.extend(p)
|
||||
self.last_col = lc
|
||||
def flush(self):
|
||||
self.stream.flush()
|
||||
|
||||
|
||||
class Log(object):
|
||||
@@ -192,80 +129,4 @@ class Log(object):
|
||||
o.close()
|
||||
|
||||
|
||||
class DevNull(Log):
|
||||
|
||||
def __init__(self):
|
||||
Log.__init__(self, level=Log.ERROR)
|
||||
self.outputs = []
|
||||
|
||||
|
||||
class ThreadSafeLog(Log):
|
||||
exception_traceback_level = Log.DEBUG
|
||||
|
||||
def __init__(self, level=Log.INFO):
|
||||
Log.__init__(self, level=level)
|
||||
self._lock = Lock()
|
||||
|
||||
def prints(self, *args, **kwargs):
|
||||
with self._lock:
|
||||
Log.prints(self, *args, **kwargs)
|
||||
|
||||
def print_with_flush(self, *args, **kwargs):
|
||||
with self._lock:
|
||||
Log.print_with_flush(self, *args, **kwargs)
|
||||
|
||||
def exception(self, *args, **kwargs):
|
||||
limit = kwargs.pop('limit', None)
|
||||
with self._lock:
|
||||
Log.print_with_flush(self, ERROR, *args, **kwargs)
|
||||
Log.print_with_flush(self, self.exception_traceback_level,
|
||||
traceback.format_exc(limit))
|
||||
|
||||
|
||||
class ThreadSafeWrapper(Log):
|
||||
|
||||
def __init__(self, other_log):
|
||||
Log.__init__(self, level=other_log.filter_level)
|
||||
self.outputs = list(other_log.outputs)
|
||||
self._lock = Lock()
|
||||
|
||||
def prints(self, *args, **kwargs):
|
||||
with self._lock:
|
||||
Log.prints(self, *args, **kwargs)
|
||||
|
||||
def print_with_flush(self, *args, **kwargs):
|
||||
with self._lock:
|
||||
Log.print_with_flush(self, *args, **kwargs)
|
||||
|
||||
|
||||
class GUILog(ThreadSafeLog):
|
||||
"""
|
||||
Logs in HTML and plain text as unicode. Ideal for display in a GUI context.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
ThreadSafeLog.__init__(self, level=self.DEBUG)
|
||||
self.outputs = [UnicodeHTMLStream()]
|
||||
|
||||
def clear(self):
|
||||
self.outputs[0].clear()
|
||||
|
||||
@property
|
||||
def html(self):
|
||||
return self.outputs[0].html
|
||||
|
||||
@property
|
||||
def plain_text(self):
|
||||
return u''.join(self.outputs[0].plain_text)
|
||||
|
||||
def dump(self):
|
||||
return self.outputs[0].dump()
|
||||
|
||||
def load(self, dump):
|
||||
return self.outputs[0].load(dump)
|
||||
|
||||
def append_dump(self, dump):
|
||||
return self.outputs[0].append_dump(dump)
|
||||
|
||||
|
||||
default_log = Log()
|
||||
|
||||
Reference in New Issue
Block a user