Example #1
0
def gen_binary_op_func(python_op):
    src_lines = ['def f(lhs, rhs):']
    if "torch" in python_op:
        src_lines.append(f'  return {python_op}(lhs, rhs)\n')
    else:
        src_lines.append(f'  return lhs {python_op} rhs\n')

    code_str = '\n'.join(src_lines)
    g = {'torch': torch}
    builtins.exec(code_str, g)
    return g["f"]
Example #2
0
 def _exec(self, player, msg, channel):
     _a = ""
     _b = ""
     for i in msg[1:]:
         _a = _a + i + " "
     for i in _a:
         if i == "\"":
             _b = _b + i
         else:
             _b = _b + i
     player.tell("Executing: " + _b)
     builtins.exec("player.tell(" + _b + ")")
Example #3
0
 def __call__(self, *args, **kwargs):
     """
     Overrides the exec builtin so it understands pysh pipelines.
     """
     if len(args) and hasattr(args[0], '__autoexpr__'):
         return expr.__autoexpr__()
     else:
         import builtins
         return builtins.exec(*args, **kwargs)
Example #4
0
def execute_script(script_name: str, options: Any, output_path: str):
    sampler = sample(options.interval, 0, output_path)

    ctx = None
    try:
        print(f"Executing the given script {script_name}")
        with open(script_name, "rb") as f:
            code_object = compile(f.read(), script_name, "exec")
            # Start to sampling
            ctx = sampler.begin(script_name)
            globals_ctx = locals_ctx = {"__name__": "__main__"}
            exec(code_object, globals_ctx, locals_ctx)
    finally:
        if ctx:
            sampler.end(ctx)
        if timer_started():
            stop_timer()
        print(f"Wrote sampling result to {output_path}")
Example #5
0
def exec(source, globals=None, locals=None, forbidden=False, builtins=False):
    """Similar to the built-in function exec().

    Works with Pytuguês code."""

    if globals is None:
        globals = {}

    if builtins:
        update_builtins(forbidden)
    else:
        globals.update(tugalib_namespace(forbidden))

    if isinstance(source, str):
        code = transpile(source)
    else:
        code = source

    return _builtins.exec(code, locals, globals)
Example #6
0
 def exec_module(self, module: types.ModuleType) -> None:
     setattr(module, "__file__", self.get_filename(module.__name__))
     builtins.exec(self.get_code(module.__spec__), module.__dict__)
     log.debug(f"Executed module '{module.__name__}'")
Example #7
0
def exec(code, *args, **kwargs):
    code, debug, original = translate(code)
    try:
        return __builtins__.exec(code, *args, **kwargs)
    except Exception as e:
        exception_handler(e, debug, original)
Example #8
0
def main():
    argparser = argparse.ArgumentParser(description=f"MíngShé {__version__}")
    argparser.add_argument("file", help="The .she file", nargs="?")
    argparser.add_argument(
        "--python",
        help="Python version. e.g. 3.7",
        default=".".join(map(str, sys.version_info[:2])),
    )
    argparser.add_argument("--compile",
                           dest="compile",
                           action="store_true",
                           help="Only compile")
    argparser.add_argument("-c",
                           dest="cmd",
                           action="store_true",
                           help="Run a short command")
    argparser.add_argument(
        "-v",
        "--verbose",
        action="count",
        default=0,
        help="Repeat for more debug output. e.g. -vv -vvv -vvvv",
    )

    args = argparser.parse_args()
    verbose = args.verbose
    verbose_tokenizer = verbose >= 3
    verbose_parser = verbose == 2 or verbose >= 4

    if verbose:
        logging.getLogger("mingshe").setLevel(logging.DEBUG)
        logging.basicConfig()

    python = tuple(
        map(int,
            re.fullmatch(r"(\d+)\.(\d+)", args.python).groups()))

    global_vars = {"__name__": "__main__"}

    write_to_py = lambda x: sys.stdout.write(x)

    if not args.cmd:
        if args.file is None:
            mingshe_code = sys.stdin.readable() and sys.stdin.read()
            filename = "<stdin>"
        else:
            _filepath = Path(args.file)
            mingshe_code = _filepath.read_text(encoding="utf8")
            filename = _filepath.absolute().__str__()
            write_to_py = _filepath.with_suffix(".py").absolute().write_text
        global_vars["__file__"] = filename
    else:
        mingshe_code = args.file
        filename = "<string>"

    ast_obj = compile(
        mingshe_code,
        filename=filename,
        verbose_tokenizer=verbose_tokenizer,
        verbose_parser=verbose_parser,
        py_version=python,
    )

    if args.compile:
        py_text = ast.unparse(ast_obj)
        write_to_py(py_text, encoding="utf8")
    else:
        sys.path.insert(0, str(Path(".").absolute()))
        install_meta(".she")  # 无论 .pth 是否加载均可解析 .she 文件
        builtins.exec(builtins.compile(ast_obj, filename, "exec"), global_vars)
Example #9
0
divmod._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.divmod)(*args, **kwargs),
    builtins.divmod)
enumerate = functools.update_wrapper(
    lambda *args, **kwargs: builtins.enumerate(*args, **kwargs),
    builtins.enumerate)
enumerate._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.enumerate)(*args, **kwargs),
    builtins.enumerate)
eval = functools.update_wrapper(
    lambda *args, **kwargs: builtins.eval(*args, **kwargs), builtins.eval)
eval._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.eval)(*args, **kwargs),
    builtins.eval)
exec = functools.update_wrapper(
    lambda *args, **kwargs: builtins.exec(*args, **kwargs), builtins.exec)
exec._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.exec)(*args, **kwargs),
    builtins.exec)
float = functools.update_wrapper(
    lambda *args, **kwargs: builtins.float(*args, **kwargs), builtins.float)
float._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.float)(*args, **kwargs),
    builtins.float)
format = functools.update_wrapper(
    lambda *args, **kwargs: builtins.format(*args, **kwargs), builtins.format)
format._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.format)(*args, **kwargs),
    builtins.format)
frozenset = functools.update_wrapper(
    lambda *args, **kwargs: builtins.frozenset(*args, **kwargs),
import builtins

# exec being part of builtins is Python 3 only
builtins.exec("print(42)")  # $getCode="print(42)"
Example #11
0
import builtins

builtins.copyright()
builtins.credits()
builtins.exec()
builtins.exit()
builtins.license()
builtins.object

builtins.quit()
builtins.exit()
builtins.zip()
Example #12
0
 def exec(self, globals, locals):
     if globals is None:
         globals = {}
     globals.update(pytuga.tugalib_namespace(forbidden=True))
     builtins.exec(self.transpiled, globals, locals)