2011-12-30 3 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

未解決のコードと特定のエラーまたはトレースバックを示してください。問題を示して自分のコードの –

+0

縮小版: 'インポート・プロファイル デフG(X): パス デフF(): X = 0 profile.run(G '(x)は') F( ) ' しかし、これは" NameError:name 'g'が定義されていません "を示しています。とにかく、同じ問題があり、profile.runctxが問題を解決します。みんなありがとう! –

答えて

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} 

>>> 

this documentにもrunctx()参照してください。