4 个回答

3

编辑(我把我的“回答”删掉了,因为Petr Viktorin的解释更有道理)。但我会留下为什么它没有按预期工作的解释。

看了一下profile.py里的代码(Python 2.7.2),我发现Profile类的方法是这样的:

def run(self, cmd):
    import __main__
    dict = __main__.__dict__
    return self.runctx(cmd, dict, dict)

def runctx(self, cmd, globals, locals):
    self.set_cmd(cmd)
    sys.setprofile(self.dispatcher)
    try:
        exec cmd in globals, locals
    finally:
        sys.setprofile(None)
    return self

在runctx()这个函数里,exec语句使用的是__main__.__dict__作为全局和局部字典,所以profile.run()只能找到在运行的应用程序顶层字典中定义的变量。

7

正如John Gaines Jr.所说,profile.run()在作用域方面有一些问题。不过,你可以直接使用runctx,配合globals()和locals(),明确地提供上下文:

profile.runctx('fact(int(x)); print', globals(), locals())

明确总比模糊好 :)

6

这个分析工具接收到一个字符串,然后试图去理解它。你给的字符串是 profile.run('fact(int(x)); print'),而里面的 x 只是字符串的一部分,不能被当作一个变量来处理。为了让它正常工作,你需要把 x 的值直接放到字符串里。试试这样做:

profile.run('fact(int(%s)); print' % x)
profile.run('factMemoized(int(%s)); print' % x)

撰写回答