예제 #1
0
    def parse_args(self, *args, **kwargs):
        self.history.append({"name": "parse_args", "args": args, "kwargs": kwargs})
        from prestring.python import Module, LazyArgumentsAndKeywords

        def _make_args(history, default=""):
            name = history["name"]
            if name == "__init__":
                name = default
            kwargs = {k: repr(v) for k, v in history["kwargs"].items()}
            args = [repr(v) for v in history["args"]]
            return f"{name}({LazyArgumentsAndKeywords(args, kwargs)})"

        m = Module()
        with m.def_("Main"):
            m.import_("argparse")
            m.stmt(f"parser = argparse.ArgumentParser{_make_args(self.history[0])}")
            for x in self.history[1:-1]:
                m.stmt(f"parser.{_make_args(x)}")
            m.stmt(f"args = parser.{_make_args(self.history[-1])}")
            m.stmt("main(**vars(args))")

        with m.if_("__name__ == '__main__'"):
            m.stmt("Main()")

        print(m)
        sys.exit(0)
예제 #2
0
    def parse_args(self, *args, **kwargs):
        self.history.append({"name": "parse_args", "args": args, "kwargs": kwargs})
        from prestring.python import Module, LazyArgumentsAndKeywords

        def _make_call_stmt(history, default=""):
            name = history["name"]
            if name == "__init__":
                name = default
            kwargs = {k: repr(v) for k, v in history["kwargs"].items()}
            args = [repr(v) for v in history["args"]]
            return f"{name}({LazyArgumentsAndKeywords(args, kwargs)})"

        m = Module()
        m.sep()
        with m.def_("main"):
            m.import_("argparse")
            m.stmt(f"parser = argparse.ArgumentParser{_make_call_stmt(self.history[0])}")
            m.stmt("parser.print_usage = parser.print_help")
            for x in self.history[1:-1]:
                m.stmt(f"parser.{_make_call_stmt(x)}")
            m.stmt(f"args = parser.{_make_call_stmt(self.history[-1])}")
            m.stmt(f"{self.fn.__name__}(**vars(args))")

        with m.if_("__name__ == '__main__'"):
            m.stmt("main()")

        with open(inspect.getsourcefile(self.fn)) as rf:
            source = rf.read()
        rx = re.compile("(?:@([\S]+\.)?as_command.*|^.*import ascommand.*)\n", re.MULTILINE)
        exposed = rx.sub("", "".join(source))
        print(exposed)
        print(m)
        sys.exit(0)
예제 #3
0
    def parse_args(self, *args, **kwargs):
        self.history.append({
            "name": "parse_args",
            "args": args,
            "kwargs": kwargs
        })
        from prestring.python import Module, LazyArgumentsAndKeywords

        def _make_args(history, default=""):
            name = history["name"]
            if name == "__init__":
                name = default
            kwargs = {k: repr(v) for k, v in history["kwargs"].items()}
            args = [repr(v) for v in history["args"]]
            return f"{name}({LazyArgumentsAndKeywords(args, kwargs)})"

        m = Module()
        with m.def_("Main"):
            m.import_("argparse")
            m.stmt(
                f"parser = argparse.ArgumentParser{_make_args(self.history[0])}"
            )
            for x in self.history[1:-1]:
                m.stmt(f"parser.{_make_args(x)}")
            m.stmt(f"args = parser.{_make_args(self.history[-1])}")
            m.stmt("main(**vars(args))")

        with m.if_("__name__ == '__main__'"):
            m.stmt("Main()")

        print(m)
        sys.exit(0)
예제 #4
0
import inspect
from yaml.constructor import Constructor
from prestring.python import Module

m = Module()
m.from_("yaml.constructor", "Constructor")
m.sep()
with m.class_("WrappedConstructor", "Constructor"):
    with m.def_("wrap", "self", "path", "name", "node", "r"):
        with m.if_("r is None"):
            m.stmt("return r")
        m.stmt('# print("@", id(r), repr(r))')
        m.stmt("mem[id(r)] = node")
        m.stmt("return r")

    seen = set()
    for cls in Constructor.mro():
        for name, attr in cls.__dict__.items():
            if name in seen:
                continue
            seen.add(name)
            if name.startswith("construct_") and callable(attr):
                sigs = inspect.signature(attr)
                m.stmt("def {}{}:", name, sigs)
                with m.scope():
                    args = []
                    for v in sigs.parameters.values():
                        if v.name == "self":
                            continue
                        if v.default is inspect._empty:
                            args.append(str(v))
예제 #5
0
from prestring.python import Module

m = Module()

with m.def_("main"):
    m.stmt("print('hello world')")

with m.if_("__name__ == '__main__'"):
    m.stmt("main()")

print(m)
예제 #6
0
from prestring.python import Module
from prestring.python._codeobject import CodeobjectModule

m = Module()
co = CodeobjectModule(m)
re = co.import_("re")
sys = co.import_("sys")

m.sep()
pattern = co.let(
    "pattern",
    re.compile(
        r"^(?P<label>DEBUG|INFO|WARNING|ERROR|CRITICAL):\s*(?P<message>\S+)",
        re.IGNORECASE,
    ),
)

with m.for_("line", sys.stdin):
    matched = co.let("matched", pattern.search(co.symbol("line")))
    with m.if_(f"{matched} is not None"):
        m.stmt("print(matched.groupdict())")
print(m)
예제 #7
0
from prestring.python import Module

m = Module()

m.import_("re")
m.import_("sys")
m.sep()
m.stmt(
    "pattern = re.compile({!r}, re.IGNORECASE)",
    r"^(?P<label>DEBUG|INFO|WARNING|ERROR|CRITICAL):\s*(?P<message>\S+)",
)

with m.for_("line", "sys.stdin"):
    m.stmt("m = pattern.search(line)")
    with m.if_("m is not None"):
        m.stmt("print(m.groupdict())")
print(m)