在行分析时注释掉 @profile 装饰器

commenting out @profile decorators when line-profiling

Python 行分析的流行解决方案似乎是 kernprof -l script.py,它需要向要分析的函数添加“@profile”装饰器。 运行 没有 as python script.py 的相同代码会抱怨 "name 'profile' not defined" 所以你必须注释掉 @profile 行。有什么好的解决方法可以在 "profile" 和非配置文件模式之间切换而不必注释掉这些行?

您可以尝试在脚本顶部添加类似这样的内容:

try:
    profile  # throws an exception when profile isn't defined
except NameError:
    profile = lambda x: x   # if it's not defined simply ignore the decorator.

如果 profile 函数未定义,您可以将其定义为无操作装饰器。