コード例 #1
0
def test_enable_disable():
    assert not prof.is_enabled()
    prof.disable()
    assert not prof.is_enabled()
    prof.enable()
    assert prof.is_enabled()
    prof.disable()
    assert not prof.is_enabled()
コード例 #2
0
ファイル: clgen.py プロジェクト: SpringRi/phd
def RunWithErrorHandling(function_to_run: typing.Callable, *args,
                         **kwargs) -> typing.Any:
    """
  Runs the given method as the main entrypoint to a program.

  If an exception is thrown, print error message and exit. If FLAGS.debug is
  set, the exception is not caught.

  Args:
    function_to_run: The function to run.
    *args: Arguments to be passed to the function.
    **kwargs: Arguments to be passed to the function.

  Returns:
    The return value of the function when called with the given args.
  """
    if FLAGS.clgen_debug:
        # Enable verbose stack traces. See: https://pymotw.com/2/cgitb/
        import cgitb
        cgitb.enable(format='text')
        return function_to_run(*args, **kwargs)

    try:

        def RunContext():
            """Run the function with arguments."""
            return function_to_run(*args, **kwargs)

        if prof.is_enabled():
            return cProfile.runctx('RunContext()',
                                   None,
                                   locals(),
                                   sort='tottime')
        else:
            return RunContext()
    except app.UsageError as err:
        # UsageError is handled by the call to app.run(), not here.
        raise err
    except errors.UserError as err:
        logging.error("%s (%s)", err, type(err).__name__)
        sys.exit(1)
    except KeyboardInterrupt:
        Flush()
        print("\nReceived keyboard interrupt, terminating", file=sys.stderr)
        sys.exit(1)
    except errors.File404 as e:
        Flush()
        LogException(e)
        sys.exit(1)
    except Exception as e:
        Flush()
        LogExceptionWithStackTrace(e)
        sys.exit(1)
コード例 #3
0
ファイル: cli.py プロジェクト: yasutakawada/clgen
def run(method, *args, **kwargs):
    """
    Runs the given method as the main entrypoint to a program.

    If an exception is thrown, print error message and exit.

    If environmental variable DEBUG=1, then exception is not caught.

    Parameters
    ----------
    method : function
        Function to execute.
    *args
        Arguments for method.
    **kwargs
        Keyword arguments for method.

    Returns
    -------
    method(*args, **kwargs)
    """
    def _user_message(exception):
        log.fatal("""\
{err} ({type})

Please report bugs at <https://github.com/ChrisCummins/clgen/issues>\
""".format(err=e, type=type(e).__name__))

    def _user_message_with_stacktrace(exception):
        # get limited stack trace
        def _msg(i, x):
            n = i + 1

            filename = fs.basename(x[0])
            lineno = x[1]
            fnname = x[2]

            loc = "{filename}:{lineno}".format(**vars())
            return "      #{n}  {loc: <18} {fnname}()".format(**vars())

        _, _, tb = sys.exc_info()
        NUM_ROWS = 5  # number of rows in traceback

        trace = reversed(traceback.extract_tb(tb, limit=NUM_ROWS+1)[1:])
        message = "\n".join(_msg(*r) for r in enumerate(trace))

        log.fatal("""\
{err} ({type})

  stacktrace:
{stack_trace}

Please report bugs at <https://github.com/ChrisCummins/clgen/issues>\
""".format(err=e, type=type(e).__name__, stack_trace=message))

    # if DEBUG var set, don't catch exceptions
    if os.environ.get("DEBUG", None):
        # verbose stack traces. see: https://pymotw.com/2/cgitb/
        import cgitb
        cgitb.enable(format='text')

        return method(*args, **kwargs)

    try:
        def runctx():
            return method(*args, **kwargs)

        if prof.is_enabled() and log.is_verbose():
            return cProfile.runctx('runctx()', None, locals(), sort='tottime')
        else:
            return runctx()
    except clgen.UserError as err:
        log.fatal(err, "(" + type(err).__name__  + ")")
    except KeyboardInterrupt:
        sys.stdout.flush()
        sys.stderr.flush()
        print("\nkeyboard interrupt, terminating", file=sys.stderr)
        sys.exit(1)
    except clgen.UserError as e:
        _user_message(e)
    except clgen.File404 as e:
        _user_message(e)
    except Exception as e:
        _user_message_with_stacktrace(e)
コード例 #4
0
ファイル: test_prof.py プロジェクト: ChrisCummins/labm8
 def test_enable_disable(self):
     self.assertTrue(prof.is_enabled())
     prof.disable()
     self.assertFalse(prof.is_enabled())
     prof.enable()
     self.assertTrue(prof.is_enabled())