Advertisement
Guest User

localise_exceptions.py

a guest
Aug 26th, 2010
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. # Python 3.
  2. import traceback, sys, re
  3.  
  4. translations = r"""
  5. ZeroDivisionError: division by zero
  6. DK: division med 0
  7. FR: division par zéro
  8. ES: división por cero
  9.  
  10. AttributeError: '(\w+)' object has no attribute '(\w+)'
  11. DK: '\1' objektet har ingen attribut '\2'
  12. ES: No hay '\1' attribute '\2'
  13. DE: '\1' hat keiner Attribute beim Name '\2'
  14. FR: '\1' n'a pas d'attribut '\2'
  15. """
  16.  
  17. def _parse_messages():
  18.     messages = []
  19.     pattern = None
  20.     translate_map = None
  21.     for linx in translations.split('\n'):
  22.         lin = linx.rstrip()
  23.         if lin != '':
  24.             if pattern is None:
  25.                 pattern = lin
  26.                 translate_map = {}
  27.                 messages.append((pattern, translate_map))
  28.             else:
  29.                 lang, msg = lin.split(':', 1)
  30.                 msg = msg.lstrip()
  31.                 translate_map[lang] = msg
  32.         else:
  33.             pattern = None
  34.             translate_map = None
  35.     return messages
  36. messages = _parse_messages()
  37. del _parse_messages
  38.  
  39. def translate_line(line, language):
  40.     if language is None:
  41.         return line
  42.     for pattern, translate_map in messages:
  43.         if re.match(pattern, line) is not None and language in translate_map:
  44.             return line.split(':',1)[0] + ': ' + re.sub(pattern, translate_map[language], line)
  45.     else:
  46.         return line
  47.  
  48. def translate(text, language):
  49.     return '\n'.join(translate_line(line, language) for line in text.split('\n'))
  50.  
  51. def install_excepthook(language):
  52.     def excepthook(type, value, tb):
  53.         # print(traceback.format_exception(type, value, tb))
  54.         print(translate('\n'.join(traceback.format_exception(type, value, tb)), language), file=sys.stderr)
  55.     sys.excepthook = excepthook
  56.  
  57. def print_translated_tb(language):
  58.     print(translate(traceback.format_exc(), language), file=sys.stderr)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement