Hi
I have a usecase where i create some code at runtime and execute it,
i am facing issue in getting proper error traceback when i run the generated code using exec
consider below MRC
code = """
def my_method():
def internal_method():
raise RuntimeError("absxsx")
internal_method()
"""
if __name__ == "__main__":
import linecache
scope = {}
filename = "<dummy-filename>"
compiled_code = compile(code, filename, "exec")
if filename not in linecache.cache:
linecache.cache[filename] = (
len(code),
None,
code.splitlines(keepends=True),
filename,
)
exec(compiled_code , scope, scope) # noqa: S102
fun = scope["my_method"]
fun()
This gives me below error traceback
Traceback (most recent call last):
File "temp2.py", line 28, in <module>
fun()
File "<dummy-filename>", line 6, in my_method
File "<dummy-filename>", line 4, in internal_method
RuntimeError: absxsx
However if i invoke my_method
directly i get proper traceback
def my_method():
def internal_method():
raise RuntimeError("absxsx")
internal_method()
if __name__ == "__main__":
my_method()
resultant traceback is
Traceback (most recent call last):
File "temp2.py", line 12, in <module>
my_method()
File "temp2.py", line 8, in my_method
internal_method()
File "temp2.py", line 6, in internal_method
raise RuntimeError("absxsx")
RuntimeError: absxsx
i tried to look into it and found that FrameSummary.line attribute is empty because it is not able to get source code but if i am adding it to linecache it should be able to get the source ig?
currently i tried to get it working by writting source code in tempfile and compiling it then it works but i was wondering if there is a way to do this without writting a tempfile
something like
scope = {linecache: linecache} # does not work :(
exec(source_code, scope, scope)
so that linecache is available
wanted to know if there is better way to do this
i am working with systems having py3.8+
Thanks.