Ignore exceptions when printing error messages

This commit is contained in:
Kovid Goyal 2017-01-10 17:17:23 +05:30
parent 9c501b37ea
commit 0d38a2ea31
7 changed files with 35 additions and 18 deletions

View File

@ -32,7 +32,7 @@ from .session import create_session
from .shaders import Sprites, ShaderProgram from .shaders import Sprites, ShaderProgram
from .tabs import TabManager, SpecialWindow from .tabs import TabManager, SpecialWindow
from .timers import Timers from .timers import Timers
from .utils import handle_unix_signals from .utils import handle_unix_signals, safe_print
def conditional_run(w, i): def conditional_run(w, i):
@ -145,7 +145,7 @@ class Boss(Thread):
func(*args) func(*args)
except Exception: except Exception:
import traceback import traceback
traceback.print_exc() safe_print(traceback.format_exc())
def add_child_fd(self, child_fd, read_ready, write_ready): def add_child_fd(self, child_fd, read_ready, write_ready):
self.read_dispatch_map[child_fd] = read_ready self.read_dispatch_map[child_fd] = read_ready

View File

@ -14,7 +14,7 @@ from .fast_data_types import (
CURSOR_BLOCK, CURSOR_BEAM, CURSOR_UNDERLINE CURSOR_BLOCK, CURSOR_BEAM, CURSOR_UNDERLINE
) )
import kitty.fast_data_types as defines import kitty.fast_data_types as defines
from .utils import to_color from .utils import to_color, safe_print
from .layout import all_layouts from .layout import all_layouts
from .constants import config_dir from .constants import config_dir
@ -53,7 +53,7 @@ def parse_mods(parts):
try: try:
mods |= getattr(defines, 'GLFW_MOD_' + map_mod(m.upper())) mods |= getattr(defines, 'GLFW_MOD_' + map_mod(m.upper()))
except AttributeError: except AttributeError:
print('Shortcut: {} has an unknown modifier, ignoring'.format(parts.join('+')), file=sys.stderr) safe_print('Shortcut: {} has an unknown modifier, ignoring'.format(parts.join('+')), file=sys.stderr)
return return
return mods return mods
@ -75,7 +75,7 @@ def parse_key(val, keymap):
key = parts[-1].upper() key = parts[-1].upper()
key = getattr(defines, 'GLFW_KEY_' + named_keys.get(key, key), None) key = getattr(defines, 'GLFW_KEY_' + named_keys.get(key, key), None)
if key is None: if key is None:
print('Shortcut: {} has an unknown key, ignoring'.format(val), file=sys.stderr) safe_print('Shortcut: {} has an unknown key, ignoring'.format(val), file=sys.stderr)
return return
keymap[(mods, key)] = action keymap[(mods, key)] = action
@ -194,7 +194,7 @@ def load_cached_values():
except FileNotFoundError: except FileNotFoundError:
pass pass
except Exception as err: except Exception as err:
print('Failed to load cached values with error: {}'.format(err), file=sys.stderr) safe_print('Failed to load cached values with error: {}'.format(err), file=sys.stderr)
def save_cached_values(): def save_cached_values():
@ -204,11 +204,11 @@ def save_cached_values():
f.write(json.dumps(cached_values).encode('utf-8')) f.write(json.dumps(cached_values).encode('utf-8'))
os.rename(p, cached_path) os.rename(p, cached_path)
except Exception as err: except Exception as err:
print('Failed to save cached values with error: {}'.format(err), file=sys.stderr) safe_print('Failed to save cached values with error: {}'.format(err), file=sys.stderr)
finally: finally:
try: try:
os.remove(p) os.remove(p)
except FileNotFoundError: except FileNotFoundError:
pass pass
except Exception as err: except Exception as err:
print('Failed to delete temp file for saved cached values with error: {}'.format(err), file=sys.stderr) safe_print('Failed to delete temp file for saved cached values with error: {}'.format(err), file=sys.stderr)

View File

@ -23,6 +23,7 @@ from .fast_data_types import (
glfw_set_error_callback, glfw_init, glfw_terminate, glfw_window_hint, glfw_set_error_callback, glfw_init, glfw_terminate, glfw_window_hint,
glfw_swap_interval, glfw_wait_events, Window glfw_swap_interval, glfw_wait_events, Window
) )
from .utils import safe_print
def option_parser(): def option_parser():
@ -78,7 +79,7 @@ def dispatch_pending_calls(boss):
func(*args) func(*args)
except Exception: except Exception:
import traceback import traceback
traceback.print_exc() safe_print(traceback.format_exc())
boss.ui_timers() boss.ui_timers()
@ -90,7 +91,7 @@ def run_app(opts, args):
try: try:
viewport_size.width, viewport_size.height = map(int, ws) viewport_size.width, viewport_size.height = map(int, ws)
except Exception: except Exception:
print('Invalid cached window size, ignoring', file=sys.stderr) safe_print('Invalid cached window size, ignoring', file=sys.stderr)
viewport_size.width = max(100, viewport_size.width) viewport_size.width = max(100, viewport_size.width)
viewport_size.height = max(80, viewport_size.height) viewport_size.height = max(80, viewport_size.height)
window = Window( window = Window(
@ -120,7 +121,7 @@ def on_glfw_error(code, msg):
msg = msg.decode('utf-8') msg = msg.decode('utf-8')
except Exception: except Exception:
msg = repr(msg) msg = repr(msg)
print('[glfw error] ', msg, file=sys.stderr) safe_print('[glfw error] ', msg, file=sys.stderr)
def main(): def main():

View File

@ -5,6 +5,14 @@
import re import re
from binascii import unhexlify, hexlify from binascii import unhexlify, hexlify
def safe_print(*a, **k):
try:
print(*a, **k)
except Exception:
pass
names = 'xterm-kitty', 'KovIdTTY' names = 'xterm-kitty', 'KovIdTTY'
termcap_aliases = { termcap_aliases = {
@ -432,7 +440,7 @@ def get_capabilities(query_string):
try: try:
val = queryable_capabilities[termcap_aliases[name]] val = queryable_capabilities[termcap_aliases[name]]
except Exception as e: except Exception as e:
print(ERROR_PREFIX, 'Unknown terminfo property:', name) safe_print(ERROR_PREFIX, 'Unknown terminfo property:', name)
raise raise
ans.append(q + '=' + hexlify(str(val))) ans.append(q + '=' + hexlify(str(val)))
return b'\033P1+r' + ';'.join(ans).encode('utf-8') + b'\033\\' return b'\033P1+r' + ';'.join(ans).encode('utf-8') + b'\033\\'

View File

@ -6,6 +6,7 @@ from collections import namedtuple
from operator import itemgetter from operator import itemgetter
from time import monotonic from time import monotonic
from .utils import safe_print
Event = namedtuple('Event', 'at callback args') Event = namedtuple('Event', 'at callback args')
get_at = itemgetter(0) get_at = itemgetter(0)
@ -54,4 +55,4 @@ class Timers:
ev.callback(*ev.args) ev.callback(*ev.args)
except Exception: except Exception:
import traceback import traceback
traceback.print_exc() safe_print(traceback.format_exc())

View File

@ -23,6 +23,13 @@ wcwidth_native.argtypes = [ctypes.c_wchar]
wcwidth_native.restype = ctypes.c_int wcwidth_native.restype = ctypes.c_int
def safe_print(*a, **k):
try:
print(*a, **k)
except Exception:
pass
@lru_cache(maxsize=2**13) @lru_cache(maxsize=2**13)
def wcwidth(c: str) -> int: def wcwidth(c: str) -> int:
ans = min(2, wcwidth_native(c)) ans = min(2, wcwidth_native(c))
@ -37,7 +44,7 @@ def timeit(name, do_timing=False):
st = monotonic() st = monotonic()
yield yield
if do_timing: if do_timing:
print('Time for {}: {}'.format(name, monotonic() - st)) safe_print('Time for {}: {}'.format(name, monotonic() - st))
def sanitize_title(x): def sanitize_title(x):

View File

@ -20,7 +20,7 @@ from .fast_data_types import (
from .keys import key_map from .keys import key_map
from .mouse import encode_mouse_event, PRESS, RELEASE, MOVE, DRAG from .mouse import encode_mouse_event, PRESS, RELEASE, MOVE, DRAG
from .terminfo import get_capabilities from .terminfo import get_capabilities
from .utils import sanitize_title, get_primary_selection, parse_color_set from .utils import sanitize_title, get_primary_selection, parse_color_set, safe_print
class Window: class Window:
@ -322,13 +322,13 @@ class Window:
if a[0] == 'draw': if a[0] == 'draw':
if a[1] is None: if a[1] is None:
if self.draw_dump_buf: if self.draw_dump_buf:
print('draw', ''.join(self.draw_dump_buf)) safe_print('draw', ''.join(self.draw_dump_buf))
self.draw_dump_buf = [] self.draw_dump_buf = []
else: else:
self.draw_dump_buf.append(a[1]) self.draw_dump_buf.append(a[1])
else: else:
if self.draw_dump_buf: if self.draw_dump_buf:
print('draw', ''.join(self.draw_dump_buf)) safe_print('draw', ''.join(self.draw_dump_buf))
self.draw_dump_buf = [] self.draw_dump_buf = []
print(*a) safe_print(*a)
# }}} # }}}