| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
import io |
| 5 |
import sys |
| 6 |
import time |
| 7 |
|
| 8 |
from polyglot.builtins import as_bytes, as_unicode |
| 9 |
|
| 10 |
|
| 11 |
def is_binary(stream): |
| 12 |
mode = getattr(stream, 'mode', None) |
| 13 |
if mode: |
| 14 |
return 'b' in mode |
| 15 |
return not isinstance(stream, io.TextIOBase) |
| 16 |
|
| 17 |
|
| 18 |
def prints(*a, **kw): |
| 19 |
"Print either unicode or bytes to either binary or text mode streams" |
| 20 |
stream = kw.get('file', sys.stdout) |
| 21 |
if stream is None: |
| 22 |
return |
| 23 |
sep, end = kw.get('sep'), kw.get('end') |
| 24 |
if sep is None: |
| 25 |
sep = ' ' |
| 26 |
if end is None: |
| 27 |
end = '\n' |
| 28 |
if is_binary(stream): |
| 29 |
encoding = getattr(stream, 'encoding', None) or 'utf-8' |
| 30 |
a = (as_bytes(x, encoding=encoding) for x in a) |
| 31 |
sep = as_bytes(sep) |
| 32 |
end = as_bytes(end) |
| 33 |
else: |
| 34 |
a = (as_unicode(x, errors='replace') for x in a) |
| 35 |
sep = as_unicode(sep) |
| 36 |
end = as_unicode(end) |
| 37 |
for i, x in enumerate(a): |
| 38 |
if sep and i != 0: |
| 39 |
stream.write(sep) |
| 40 |
stream.write(x) |
| 41 |
if end: |
| 42 |
stream.write(end) |
| 43 |
if kw.get('flush'): |
| 44 |
try: |
| 45 |
stream.flush() |
| 46 |
except Exception: |
| 47 |
pass |
| 48 |
|
| 49 |
|
| 50 |
def debug_print(*args, **kw): |
| 51 |
""" |
| 52 |
Prints debug information to the console if debugging is enabled. |
| 53 |
|
| 54 |
This function prints a message prefixed with a timestamp showing the elapsed time |
| 55 |
since the first call to this function. The message is printed only if debugging is enabled. |
| 56 |
|
| 57 |
Parameters: |
| 58 |
*args : tuple |
| 59 |
Variable length argument list to be printed. |
| 60 |
**kw : dict |
| 61 |
Arbitrary keyword arguments to be passed to the `print` function. |
| 62 |
|
| 63 |
Attributes: |
| 64 |
base_time : float |
| 65 |
The timestamp of the first call to this function. Stored as an attribute of the function. |
| 66 |
|
| 67 |
Behavior: |
| 68 |
- On the first call, initializes `base_time` to the current time using `time.monotonic()`. |
| 69 |
- If `is_debugging()` returns True, prints the elapsed time since `base_time` along with the provided arguments. |
| 70 |
""" |
| 71 |
from calibre.constants import is_debugging |
| 72 |
|
| 73 |
|
| 74 |
base_time = getattr(debug_print, 'base_time', None) |
| 75 |
if base_time is None: |
| 76 |
|
| 77 |
base_time = time.monotonic() |
| 78 |
setattr(debug_print, 'base_time', base_time) |
| 79 |
|
| 80 |
|
| 81 |
if is_debugging(): |
| 82 |
|
| 83 |
prints(f'DEBUG: {time.monotonic() - base_time:6.1f}', *args, **kw) |