cProfile and name spaces.

Gelonida N gelonida at gmail.com
Fri Sep 23 12:23:57 CEST 2011


Hi

I have following piece of code in file f1.py

##### f1.py starts here #######
def f():
    pass

def main():
    import profile
    profile.run('f()')

if __name__ == '__main__':
    main()
# ------ end of f1.py ----


executing f1.py works as expected.

Now I have a file f2.py
##### f2.py starts here #######
import f1
f1.main()
# ------ end of f2.py ----


If I run f2.py

I get the error message:
. . . .
>   File "C:\Python26\lib\profile.py", line 70, in run
>     prof = prof.run(statement)
>   File "C:\Python26\lib\profile.py", line 456, in run
>     return self.runctx(cmd, dict, dict)
>   File "C:\Python26\lib\profile.py", line 462, in runctx
>     exec cmd in globals, locals
>   File "<string>", line 1, in <module>
> NameError: name 'f' is not defined

So  cProfile doesn't find my function f any more.

I can fix this by changing the code in f1.py to

profile.run('f1.f()')

However now I can't run f1.py anymore.


Is it intentional, that cProfile always uses the name space of the
initial module?

I consider it surprising especially as I did not find any mentioning of
this particularity in the documentation, which states:


> cProfile.run(command[, filename])
> 
> This function takes a single argument that can be passed to the exec
> statement, and an optional file name. In all cases this routine attempts
> to exec its first argument, and gather profiling statistics from the
> execution. If no file name is present, then this function automatically
> prints a simple profiling report, sorted by the standard name string
> (file/line/function-name) that is presented in each line. The following
> is a typical output from such a call:


I'm using python 2.6.5

The reason why I don't profile at the top level is, that I do not want
to profile some parts of the code and as I want to
conditionally profile  a cetain function within different contexts /
applications

WI have also difficulties implementing something like this in a module,
which
is not the main module.

arg1 = f(1)
arg2 = f2()
if do_profile:
    CProfile('result = function_name(arg1, arg2)', fname)
else:
    result = function_name(arg1, arg2)


Any tips / suggestions??













More information about the Python-list mailing list