Esempio n. 1
0
def call_with_import(module_name, extra_argv=[], assert_result=True):
    """Import module_name and run module.main() with given argv, capturing output."""
    pytest.register_assert_rewrite(py_str(module_name))
    print("import", module_name, "with extra_argv=" + repr(extra_argv))
    old_stdout, sys.stdout = sys.stdout, LoggingStringIO(sys.stdout)
    old_stderr, sys.stderr = sys.stderr, LoggingStringIO(sys.stderr)
    old_argv = sys.argv
    try:
        with using_coconut():
            if sys.version_info >= (2, 7):
                module = importlib.import_module(module_name)
            else:
                module = imp.load_module(module_name,
                                         *imp.find_module(module_name))
            sys.argv = [module.__file__] + extra_argv
            result = module.main()
            if assert_result:
                assert result
    except SystemExit as err:
        retcode = err.code or 0
    except BaseException:
        logger.print_exc()
        retcode = 1
    else:
        retcode = 0
    finally:
        sys.argv = old_argv
        stdout = sys.stdout.getvalue()
        stderr = sys.stderr.getvalue()
        sys.stdout = old_stdout
        sys.stderr = old_stderr
    return stdout, stderr, retcode
Esempio n. 2
0
 def cache(self, code, *args, **kwargs):
     """Version of cache that compiles Coconut code first."""
     try:
         compiled = memoized_parse_block(code)
     except CoconutException:
         logger.print_exc()
         return None
     else:
         return super(CoconutCompiler, self).cache(compiled, *args, **kwargs)
Esempio n. 3
0
def rm_path(path):
    """Delete a path."""
    if os.path.isdir(path):
        try:
            shutil.rmtree(path)
        except OSError:
            logger.print_exc()
    elif os.path.isfile(path):
        os.remove(path)
Esempio n. 4
0
def using_path(path):
    """Removes a path at the beginning and end."""
    if os.path.exists(path):
        rm_path(path)
    try:
        yield
    finally:
        try:
            rm_path(path)
        except OSError:
            logger.print_exc()
Esempio n. 5
0
 def handles_prompt_toolkit_errors_func(self, *args, **kwargs):
     if self.style is not None:
         try:
             return func(self, *args, **kwargs)
         except (KeyboardInterrupt, EOFError):
             raise
         except (Exception, AssertionError):
             logger.print_exc()
             logger.show("Syntax highlighting failed; switching to --style none.")
             self.style = None
     return func(self, *args, **kwargs)
Esempio n. 6
0
def mypy_run(args):
    """Run mypy with given arguments and return the result."""
    logger.log_cmd(["mypy"] + args)
    try:
        stdout, stderr, exit_code = run(args)
    except BaseException:
        logger.print_exc()
    else:
        for line in stdout.splitlines():
            yield line, False
        for line in stderr.splitlines():
            yield line, True
Esempio n. 7
0
 def handling_exceptions(self):
     """Performs proper exception handling."""
     try:
         with handling_broken_process_pool():
             yield
     except SystemExit as err:
         self.register_error(err.code)
     except BaseException as err:
         if isinstance(err, CoconutException):
             logger.print_exc()
         elif not isinstance(err, KeyboardInterrupt):
             traceback.print_exc()
         self.register_error(errmsg=err.__class__.__name__)
Esempio n. 8
0
 def handling_exceptions(self):
     """Performs proper exception handling."""
     try:
         with handling_broken_process_pool():
             yield
     except SystemExit as err:
         self.register_error(err.code)
     except BaseException as err:
         if isinstance(err, CoconutException):
             logger.print_exc()
         elif not isinstance(err, KeyboardInterrupt):
             traceback.print_exc()
         self.register_error(errmsg=err.__class__.__name__)
Esempio n. 9
0
def using_dest(dest=dest):
    """Makes and removes the dest folder."""
    try:
        os.mkdir(dest)
    except Exception:
        rm_path(dest)
        os.mkdir(dest)
    try:
        yield
    finally:
        try:
            rm_path(dest)
        except OSError:
            logger.print_exc()
Esempio n. 10
0
        def do_complete(self, code, cursor_pos):
            # first try with Jedi completions
            self.use_experimental_completions = True
            try:
                return super(CoconutKernel, self).do_complete(code, cursor_pos)
            except Exception:
                logger.print_exc()
                logger.warn_err(CoconutInternalException("experimental IPython completion failed, defaulting to shell completion"), force=True)

            # then if that fails default to shell completions
            self.use_experimental_completions = False
            try:
                return super(CoconutKernel, self).do_complete(code, cursor_pos)
            finally:
                self.use_experimental_completions = True
Esempio n. 11
0
 def magic(line, cell=None):
     """Provides %coconut and %%coconut magics."""
     try:
         if cell is None:
             code = line
         else:
             # first line in block is cmd, rest is code
             line = line.strip()
             if line:
                 cmd(line)
             code = cell
         compiled = parse(code)
     except CoconutException:
         logger.print_exc()
     else:
         ipython.run_cell(compiled, shell_futures=False)
Esempio n. 12
0
 def magic(line, cell=None):
     """Provides %coconut and %%coconut magics."""
     try:
         if cell is None:
             code = line
         else:
             # first line in block is cmd, rest is code
             line = line.strip()
             if line:
                 cmd(line, interact=False)
             code = cell
         compiled = parse(code)
     except CoconutException:
         logger.print_exc()
     else:
         ipython.run_cell(compiled, shell_futures=False)
Esempio n. 13
0
 def input(self, more=False):
     """Prompt for code input."""
     sys.stdout.flush()
     if more:
         msg = more_prompt
     else:
         msg = main_prompt
     if self.style is not None:
         internal_assert(prompt_toolkit is not None,
                         "without prompt_toolkit cannot highlight style",
                         self.style)
         try:
             return self.prompt(msg)
         except EOFError:
             raise  # issubclass(EOFError, Exception), so we have to do this
         except (Exception, AssertionError):
             logger.print_exc()
             logger.show_sig(
                 "Syntax highlighting failed; switching to --style none.")
             self.style = None
     return input(msg)
Esempio n. 14
0
 def handle_input(self, code):
     """Compiles Coconut interpreter input."""
     if not self.prompt.multiline:
         if not should_indent(code):
             try:
                 return self.comp.parse_block(code)
             except CoconutException:
                 pass
         while True:
             line = self.get_input(more=True)
             if line is None:
                 return None
             elif line:
                 code += "\n" + line
             else:
                 break
     try:
         return self.comp.parse_block(code)
     except CoconutException:
         logger.print_exc()
     return None
Esempio n. 15
0
 def handle_input(self, code):
     """Compiles Coconut interpreter input."""
     if not self.prompt.multiline:
         if not should_indent(code):
             try:
                 return self.comp.parse_block(code)
             except CoconutException:
                 pass
         while True:
             line = self.get_input(more=True)
             if line is None:
                 return None
             elif line:
                 code += "\n" + line
             else:
                 break
     try:
         return self.comp.parse_block(code)
     except CoconutException:
         logger.print_exc()
     return None
Esempio n. 16
0
File: util.py Progetto: pyzh/coconut
 def input(self, more=False):
     """Prompts for code input."""
     sys.stdout.flush()
     if more:
         msg = more_prompt
     else:
         msg = main_prompt
     if self.style is not None:
         if prompt_toolkit is None:
             raise CoconutInternalException(
                 "cannot highlight style without prompt_toolkit",
                 self.style)
         try:
             return prompt_toolkit.prompt(msg, **self.prompt_kwargs())
         except EOFError:
             raise  # issubclass(EOFError, Exception), so we have to do this
         except Exception:
             logger.print_exc()
             logger.show(
                 "Syntax highlighting failed; switching to --style none.")
             self.style = None
     return input(msg)
Esempio n. 17
0
 def evaluate(self):
     """Get the result of evaluating the computation graph at this node."""
     if DEVELOP:
         internal_assert(not self.been_called, "inefficient reevaluation of action " + self.name + " with tokens", self.tokens)
         self.been_called = True
     evaluated_toks = evaluate_tokens(self.tokens)
     if logger.tracing:  # avoid the overhead of the call if not tracing
         logger.log_trace(self.name, self.original, self.loc, evaluated_toks, self.tokens)
     try:
         return _trim_arity(self.action)(
             self.original,
             self.loc,
             evaluated_toks,
         )
     except CoconutException:
         raise
     except (Exception, AssertionError):
         logger.print_exc()
         error = CoconutInternalException("error computing action " + self.name + " of evaluated tokens", evaluated_toks)
         if embed_on_internal_exc:
             logger.warn_err(error)
             embed(depth=2)
         else:
             raise error