我想跟踪一个动态加载的函数。通过跟踪,我的意思是使用Python3中可用的trace
模块。
我可以使用动态加载的函数,但是trace.run()
失败:找不到函数。
这是我的代码:
from trace import Trace
import importlib
class GenerateSequenceDiagram:
def __init__(self, driver_module):
self.driver_module = __import__(driver_module)
def get_functions_called(self, driver_function):
self.driver_function = getattr(self.driver_module, driver_function)
self.driver_function()
# print(dir(self.driver_function))
# print(self.driver_function.__name__)
tracer = Trace(countfuncs=1)
tracer.run('{}()'.format(self.driver_function.__name__))
results = tracer.results()
called_functions = results.calledfuncs
for filename, modulename, funcname in sorted(called_functions):
print('filename: {}, modulename: {}, funcname: {}'.format(
filename, modulename, funcname))
results.write_results()
ob = GenerateSequenceDiagram('driver')
ob.get_functions_called('main_2')
生成的错误是:
NameError: name 'main_2' is not defined
➜ source_code_to_study git:(sequence_diagram) ✗ python3 trace_functions_called.py
Inside main_2 func
False
True
True
Traceback (most recent call last):
File "trace_functions_called.py", line 25, in <module>
ob.get_functions_called('main_2')
File "trace_functions_called.py", line 15, in get_functions_called
tracer.run('{}()'.format(self.driver_function.__name__))
File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/trace.py", line 440, in run
self.runctx(cmd, dict, dict)
File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/trace.py", line 449, in runctx
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
NameError: name 'main_2' is not defined