Dan*_*eck 3 python profiler python-2.6
我有一个相当简单的Python脚本,其中包含一个函数调用
f(var, other_var)
即一个获取几个参数的函数.所有这些参数都可以在f中访问并具有值.
当我改为打电话
cProfile.run('f(var, other_var)')
它失败并显示错误消息:
NameError: "name 'var' is not defined"
Python版本是
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?
这是因为cProfile会尝试将exec您作为字符串传递给它的代码,并且失败是因为,var在那段代码中没有定义!它使用调用范围内的变量run(),但由于你没有告诉cProfile它们不知道使用它们.请runctx改用,因为它允许您传入locals和globals字典以用于execed代码:
cProfile.runctx( "...", globals(), locals() )
Run Code Online (Sandbox Code Playgroud)