AttributeError: '模块'对象没有'maketrans'属性,在运行cProfile时

5 投票
1 回答
7186 浏览
提问于 2025-04-16 17:00

我在使用Python 2.7的时候遇到了这个错误:

    Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/lib/python2.7/cProfile.py", line 199, in <module>
    main()
  File "/usr/lib/python2.7/cProfile.py", line 165, in main
    from optparse import OptionParser
  File "/usr/lib/python2.7/optparse.py", line 77, in <module>
    import textwrap
  File "/usr/lib/python2.7/textwrap.py", line 32, in <module>
    class TextWrapper:
  File "/usr/lib/python2.7/textwrap.py", line 74, in TextWrapper
    whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
AttributeError: 'module' object has no attribute 'maketrans'

当我运行这段简单的代码时:

def blah():
    orig = ""
    for i in range(1000000):
        orig += "zim";
blah()

使用这个调用:

$ python -m cProfile string.py

我在使用Ubuntu Natty Narwhal系统,并且安装了python-profiler这个软件包(我不确定这是否必要)。

1 个回答

7

根据Python模块教程的解释:

其实,Python在寻找模块时,会查看一个叫做sys.path的变量,这个变量里列出了几个目录。这个目录列表是从包含你正在运行的脚本的目录(或者当前目录)开始的,还包括PYTHONPATH和一些默认的安装路径。这意味着,如果你知道自己在做什么,Python程序可以修改或替换这个模块搜索路径。需要注意的是,因为运行的脚本所在的目录在搜索路径中,所以脚本的名字不能和标准模块重名,否则当你导入那个模块时,Python会试图把你的脚本当作模块来加载。

比如,textwrap模块会去import string。假设你的脚本叫string.py,而且它在搜索路径中排在前面(或者至少在标准库目录之前),那么它就会被导入。但是,它并没有定义我们期待的那些函数和常量,比如它没有maketrans模块。这就是错误信息想告诉你的。

(如果你只是运行这个脚本而不进行性能分析,也会出现同样的错误。)

撰写回答