Python: scope of variables and profile.run

I want to call profile.run in my function, that is:

def g(): ... def f(): x = ... run.profile('g(x)') 

However, he says that "x is not defined" when calling run.profile. As I understand it, I have to provide the import statement before calling g (x) inside the string argument for the run.profile file, and I could do this with global variables.

Is this possible with local variables?

+4
source share
2 answers

Instead of using run() use runctx() , which allows you to provide local and global variables. For instance:

 >>> import cProfile >>> def g(x): ... print "g(%d)" % x ... >>> x=100 >>> cProfile.runctx('g(x)', {'x': x, 'g': g}, {}) g(100) 3 function calls in 0.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 <stdin>:1(g) 1 0.000 0.000 0.000 0.000 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} >>> 

See also runctx() in this document .

+13
source

Instead of x setting the function arguments, include x entire function call.

Example:

 import cProfile def g(x): print x x = """g("Hello world!")""" cProfile.run(x) 
+1
source

Source: https://habr.com/ru/post/1388646/


All Articles