def __init__(self, locals=None, use_rich=False): # noqa """This class builds upon Python's code.InteractiveConsole so as to provide friendly tracebacks. It keeps track of code fragment executed by treating each of them as an individual source file. """ _ = current_lang.translate friendly_traceback.exclude_file_from_traceback(codeop.__file__) self.fake_filename = "<friendly-console:%d>" self.counter = 1 self.old_locals = {} self.saved_builtins = {} for name in dir(builtins): self.saved_builtins[name] = getattr(builtins, name) self.rich_console = False if theme.rich_available and use_rich: try: self.rich_console = theme.init_rich_console() friendly_traceback.set_formatter("rich") except Exception: print(_("\n Installed version of Rich is too old.\n\n")) elif use_rich: print(_("\n Rich is not installed.\n\n")) super().__init__(locals=locals) self.check_for_builtins_changes() self.check_for_annotations()
def start_console(): """Starts a Friendly console with a custom formatter for IDLE""" import friendly_traceback # noqa sys.stderr = sys.stdout.shell # noqa friendly_traceback.set_formatter(idle_formatter) friendly_traceback.set_stream(idle_writer) friendly_traceback.start_console()
def install(): """Installs Friendly-traceback in the IDLE shell, with a custom formatter. For Python versions before 3.10, this is not directly supported, so a Friendly console is used instead of IDLE's shell. """ import friendly_traceback sys.stderr = sys.stdout.shell # noqa friendly_traceback.set_formatter(idle_formatter) if sys.version_info >= (3, 10): install_in_idle_shell() else: idle_writer( "Friendly-traceback cannot be installed in this version of IDLE.\n" ) idle_writer("Using Friendly's own console instead.\n") start_console()
def run(filename, lang=None, include="friendly_tb", args=None, console=True): """This function executes the code found in a python file. ``filename`` should be either an absolute path or, it should be the name of a file (filename.py) found in the same directory as the file from which ``run()`` is called. If friendly_console is set to ``False`` (the default) and the Python version is greater or equal to 3.10, ``run()`` returns an empty dict if a ``SyntaxError`` was raised, otherwise returns the dict in which the module (``filename``) was executed. If console is set to ``True`` (the default), the execution continues as an interactive session in a Friendly console, with the module dict being used as the locals dict. Other arguments include: ``lang``: language used; currently only ``en`` (default) and ``fr`` are available. ``include``: specifies what information is to be included if an exception is raised. ``args``: strings tuple that is passed to the program as though it was run on the command line as follows:: python filename.py arg1 arg2 ... """ import friendly_traceback _ = current_lang.translate sys.stderr = sys.stdout.shell # noqa friendly_traceback.set_formatter(idle_formatter) friendly_traceback.set_stream(idle_writer) filename = Path(filename) if not filename.is_absolute(): frame = inspect.stack()[1] # This is the file from which run() is called run_filename = Path(frame[0].f_code.co_filename) run_dir = run_filename.parent.absolute() filename = run_dir.joinpath(filename) if not filename.exists(): print( _("The file {filename} does not exist.").format(filename=filename)) return if not console: if sys.version_info >= (3, 10): install_in_idle_shell() elif sys.version_info < (3, 10): sys.stderr.write( "Friendly-traceback cannot be installed in this version of IDLE.\n" ) return friendly_traceback.run(filename, lang=lang, include=include, args=args, console=console)
try: from IPython.core import interactiveshell as shell from IPython.core import compilerop except ImportError: raise ValueError("IPython cannot be imported.") from friendly_traceback import ( install, exclude_file_from_traceback, explain_traceback, set_formatter, ) from friendly_traceback.console_helpers import * # noqa from friendly_traceback.console_helpers import helpers # noqa __all__ = list(helpers.keys()) __all__.append("set_formatter") shell.InteractiveShell.showtraceback = lambda self, *args, **kwargs: explain_traceback( ) shell.InteractiveShell.showsyntaxerror = ( lambda self, *args, **kwargs: explain_traceback()) exclude_file_from_traceback(shell.__file__) exclude_file_from_traceback(compilerop.__file__) install(include="friendly_tb") set_formatter("repl") print("Friendly-traceback installed.")
def __init__(self, master=None): super().__init__(master=master) friendly_traceback.set_formatter(formatter=self.formatter)
import sys import platform import friendly_traceback # Make it possible to find docs and tests source this_dir = os.path.dirname(__file__) docs_root_dir = os.path.abspath( os.path.join(this_dir, "..", "..", "friendly-traceback-docs")) assert os.path.isdir(docs_root_dir), "Separate docs repo need to exist" # sys.path.insert(0, root_dir) LANG = "fr" friendly_traceback.install() friendly_traceback.set_lang(LANG) friendly_traceback.set_formatter("pre") sys.path.insert(0, this_dir) import trb_common target = os.path.normpath( os.path.join(docs_root_dir, f"docs/source/tracebacks_{LANG}.rst")) intro_text = """ |france| Friendly tracebacks - en Français =========================================== Le but principal de friendly-traceback est de fournir des rétroactions plus conviviales que les fameux **tracebacks** de Python lorsqu'une exception survient. Ci-dessous, on peut voir quelques exemples. Le but éventuel est de documenter
import os import sys import platform import friendly_traceback # Make it possible to find docs and tests source this_dir = os.path.dirname(__file__) docs_root_dir = os.path.abspath( os.path.join(this_dir, "..", "..", "friendly-traceback-docs") ) assert os.path.isdir(docs_root_dir), "Separate docs repo need to exist" friendly_traceback.install() friendly_traceback.set_lang("en") friendly_traceback.set_formatter("markdown_docs") sys.path.insert(0, this_dir) py_version = f"{sys.version_info.major}.{sys.version_info.minor}" import trb_common target = os.path.normpath( os.path.join(docs_root_dir, f"docs/source/tracebacks_markdown.md") ) intro_text = """ # Friendly tracebacks - markdown_docs format <div class="admonition note"> <p class="admonition-title">Note</p>
<h4>{last_call_header}<h4> <pre>{last_call_source}</pre> <pre class='var'>{last_call_variables}</pre> <h4>{exception_raised_header}<h4> <pre>{exception_raised_source}</pre> <pre class='var'>{exception_raised_variables}</pre> """ end_html = "</body></html>" def html_formatter(info, level=None): items = make_empty_dict() for key in info: items[key] = info[key] return template.format(**items) friendly_traceback.set_formatter(formatter=html_formatter) try: b = a + c # noqa except Exception: friendly_traceback.explain(redirect="capture") result = begin_html + friendly_traceback.get_output() + end_html with open("test.html", "w") as f: f.write(result)