I want to get the source code of the currently running program, do some transformations (at the source-level and also at the bytecode-level), and output the new source code.
@typechecked
def module_to_bytecode(module:ModuleType)->Bytecode: # ?
#with open(module.__file__, "rb") as file:
# file.seek(16)
# mbc:bytes = file.read( )
try:
return marshal.load(module.__file__)
except ValueError as e:
raise IntrospectionError('failed to convert moduletype to bytecode') from e
@typechecked
def decompile_module(module:ModuleType)->str:
""" handles .pyc ? """
assembly:Bytecode = module_to_bytecode(module)
try:
return decompile(assembly) # TODO test
except Exception as e:
raise IntrospectionError(f"failed to decompile moduletype") from e
#if extra_tests:
# print(decompile_module(getmodule(currentframe())))
@typechecked
def introspect()->str:
""" returns the source code for the currently running module """
cf:FrameType = currentframe()
if cf is None:
raise IntrospectionError("Running on an implementation without Python stack frame support?")
cm:ModuleType = getmodule(cf)
try:
return getsource(cm)
except OSError as e:
return decompile_module(cm)