2011-12-30 70 views
4

我想我的函數中調用profile.run,即:的Python:變量的作用域和profile.run

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

然而,它說,調用run.profile當「X沒有定義」。據我所知,我必須在調用run.profile的字符串參數中的g(x)之前提供import語句,並且可以使用全局變量來完成此操作。

這是可能的局部變量?

+1

請顯示未刪節的代碼和特定的錯誤或回溯。 ) 通 DEF F(: – 2011-12-30 18:34:52

+0

簡化版本的我的代碼,顯示該問題: '導入配置 DEF G(X) x = 0的 profile.run( 'G(X)') F( )' 但是,它顯示「NameError:name'g'未定義」。 無論如何,這是同樣的問題和profile.runctx解決了這個問題。感謝大家! – 2011-12-30 19:36:47

回答

1

而不是讓x設置爲該函數的參數,有x包括整個函數調用。

例子:

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

使用run()使用runctx()它允許您提供當地人和全局代替。例如:

>>> 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} 

>>> 

runctx()this document