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?
This is because cProfile attempts to
execthe code you pass it as a string, and fails because, well,varis not defined in that piece of code! It is using the variables in the scope of the call torun(), but since you haven’t told cProfile about them it doesn’t know to use them. Userunctxinstead, since it allows you to pass in the locals and globals dictionaries to use for theexeced code: