import inspect import sys import textwrap from pathlib import Path SCRIPT_TEMPLATE = """\ #! {executable} # AUTOGENERATED USING SCRIPTIFY FOR USE IN TESTS FOR DVC {code} if __name__ == "__main__": import sys _, *argv = sys.argv func = {func!s} func(*argv) """ def scriptify(func, path=None): # you can use `breakpoint()` inside functions too # just remember to run the test in `-s` mode. code = textwrap.dedent(inspect.getsource(func)) executable = sys.executable source = SCRIPT_TEMPLATE.format( executable=executable, code=code, func=func.__name__ ) if not path: return source, None Path(path).write_text(source, encoding="utf-8") return source, f"{executable} {path}"