views:

65

answers:

1

I have a rather simple Python script that contains a function call like

f(var, other_var)

i.e. a function that gets several parameters. All those parameters can be accessed within f and have values.

When I instead call

cProfile.run('f(var, other_var)')

it fails with the error message:

NameError: "name 'var' is not defined"

Python version is

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin

What's going on here?

+2  A: 

This is because cProfile attempts to exec the code you pass it as a string, and fails because, well, var is not defined in that piece of code! It is using the variables in the scope of the call to run(), but since you haven't told cProfile about them it doesn't know to use them. Use runctx instead, since it allows you to pass in the locals and globals dictionaries to use for the execed code:

cProfile.runctx( "...", globals(), locals() )
katrielalex
I've used the profiler so many times but never in a situation that would expose this issue... thanks!
Daniel Beck