【问题标题】:Cannot import cProfile in Python 3无法在 Python 3 中导入 cProfile
【发布时间】:2013-04-07 01:27:58
【问题描述】:

我正在尝试将 cProfile 模块导入 Python 3.3.0,但出现以下错误:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    import cProfile
  File "/.../cProfile_try.py", line 12, in <module>
    help(cProfile.run)
AttributeError: 'module' object has no attribute 'run'

完整代码(cProfile_try.py)如下

import cProfile
help(cProfile.run)

L = list(range(10000000))
len(L)
# 10000000

def binary_search(L, v):
    """ (list, object) -> int

    Precondition: L is sorted from smallest to largest, and
    all the items in L can be compared to v.

    Return the index of the first occurrence of v in L, or
    return -1 if v is not in L.

    >>> binary_search([2, 3, 5, 7], 2)
    0
    >>> binary_search([2, 3, 5, 5], 5)
    2
    >>> binary_search([2, 3, 5, 7], 8)
    -1
    """

    b = 0
    e = len(L) - 1

    while b <= e:
        m = (b + e) // 2
        if L[m] < v:
            b = m + 1
        else:
            e = m - 1

    if b == len(L) or L[b] != v:
        return -1
    else:
        return b

cProfile.run('binary_search(L, 10000000)')

【问题讨论】:

  • 您在当前目录或sys.path 上的其他位置是否有在标准库之前搜索过的cProfile.py?打印cProfile.__file__ 的值。
  • @eryksun:我认为 cProfile 是要在会话中导入的模块,对吧?导入后,cProfile.run 应该可用...
  • @eryksun:谢谢!我得到了这个/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cProfile.py 作为print(cProfile.__file__) 的输出。
  • @eryksun:是的...我改用 python 2.7。对于 python 3.3,我没有得到任何输出
  • 确保您的目录中没有profile.py,因为cProfile 本身会导入错误的配置文件模块。

标签: python cprofile


【解决方案1】:

如评论中所述,可能在当前目录中意外存在名为profile.py 的文件。 cProfile 无意中使用了此文件,从而掩盖了 Python 的 profile 模块。

建议的解决方案是:

mv profile.py profiler.py

接下来,为了更好的衡量,

如果使用 Python 3:

rm __pycache__/profile.*.pyc

如果使用 Python 2:

rm profile.pyc

【讨论】:

  • 天哪,我调用了我的测试脚本profile.py。还好里面没有 run 函数!
【解决方案2】:

尝试使用“将配置文件导入为 cProfile”

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 他们为什么要这样做?他们正在尝试导入 built-in 模块cProfile。导入完全不同的东西并将其命名相同有什么帮助?
猜你喜欢
  • 2017-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多