Python:变量scope和profile.run

Python:变量scope和profile.run,python,variables,scope,profile,Python,Variables,Scope,Profile,我想在我的函数中调用profile.run,即: def g(): ... def f(): x = ... run.profile('g(x)') 但是,在调用run.profile时,会显示“x未定义”。据我所知,在调用字符串参数中的g(x)来run.profile之前,我必须提供import语句,我可以使用全局变量来完成这项工作 局部变量是否可以这样做?将x设置为函数的参数,而不是将x包含整个函数调用 例如: import cProfile def g(x):

我想在我的函数中调用profile.run,即:

def g():
    ...
def f():
    x = ...
    run.profile('g(x)')
但是,在调用run.profile时,会显示“x未定义”。据我所知,在调用字符串参数中的g(x)来run.profile之前,我必须提供import语句,我可以使用全局变量来完成这项工作


局部变量是否可以这样做?

x
设置为函数的参数,而不是将
x
包含整个函数调用

例如:

import cProfile
def g(x):
    print x
x = """g("Hello world!")"""
cProfile.run(x)
不要使用
run()。例如:

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

>>>
>>导入cProfile
>>>def g(x):
...   打印“g(%d)”%x
... 
>>>x=100
>>>runctx('g(x)',{'x':x,'g':g},{})
g(100)
在0.000 CPU秒内进行3次函数调用
订购人:标准名称
ncalls tottime percall cumtime percall文件名:lineno(函数)
1 0.000 0.000 0.000 0.000:1(克)
1    0.000    0.000    0.000    0.000 :1()
1 0.000 0.000 0.000 0.000{方法'disable'的''lsprof.Profiler'对象}
>>>

另请参见中的
runctx()

请显示未桥接的代码和特定错误或回溯。显示问题的代码的简化版本:
导入配置文件def g(x):传递def():x=0配置文件。run('g(x)')f()
但是,它显示“名称错误:名称“g”未定义”。无论如何,这是同一个问题,profile.runctx解决了这个问题。谢谢大家!