3

我有一个相当简单的 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

这里发生了什么?

4

1 回答 1

9

这是因为 cProfile 尝试将exec您作为字符串传递给它的代码,但失败了,因为var那段代码中没有定义!它在调用范围内使用变量run(),但由于您没有告诉 cProfile 关于它们,它不知道要使用它们。改为使用runctx,因为它允许您传入本地和全局字典以用于execed 代码:

cProfile.runctx( "...", globals(), locals() )
于 2010-08-11T09:57:57.700 回答