Python:变量范围和 profile.run

标签 python variables scope profile

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

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

但是,它在调用 run.profile 时显示“x is not defined”。据我所知,我必须在调用 g(x) inside string argument 到 run.profile 之前提供 import 语句,我可以用全局变量来做到这一点。

局部变量是否可行?

最佳答案

不要使用 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() .

关于Python:变量范围和 profile.run,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8682716/

相关文章:

python - 为已被 set_index() 更改的数据帧提供正常索引

python - 根据其他两列中的值,用另一个数据框中的值填充一个数据框中的新列? ( python / Pandas )

java - 不能从静态上下文中引用非静态变量

swift - : and = 之间的差异

python - 带有 __add__ 的自定义类以添加 NumPy 数组

python - 使用 FFMPEG 覆盖 Chromakey 后视频变暗

javascript - HTML 变量导致 CGI 文件出错

javascript - 如何确保变量没有通过引用传递

c# - 当前上下文中不存在该名称 - grrr

ruby-on-rails - Rails 5 - 使用 Pundit Scopes 和 Statesman 状态机 : structurally incompatible?