Python 属性错误:';模块';对象没有属性';maketrans';在运行cProfile时
使用python 2.7,我会遇到以下错误:Python 属性错误:';模块';对象没有属性';maketrans';在运行cProfile时,python,profiler,Python,Profiler,使用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
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'
使用此呼叫:
$ python -m cProfile string.py
我正在使用Ubuntu Natty Narhall,并安装了包python profiler(我不知道这是否必要)。如图所示:
实际上,模块是在变量sys.path给定的目录列表中搜索的,该变量是从包含输入脚本(或当前目录)、PYTHONPATH和依赖于安装的默认值的目录初始化的。这允许知道自己在做什么的Python程序修改或替换模块搜索路径。请注意,因为包含正在运行的脚本的目录位于搜索路径上,所以脚本的名称不能与标准模块的名称相同,否则Python将在导入该模块时尝试将脚本作为模块加载
textwrap
不导入字符串。您的脚本名为string.py
,在搜索路径上位于第一位(或至少在stdlib目录之前),因此它将被导入。但它没有定义预期的函数和常量,例如,它没有maketrans
模块。这就是错误告诉你的
(如果只运行脚本而不进行分析,也会出现同样的错误。)故事的寓意:永远不要将程序命名为与stdlib模块相同的名称。哇,这是一个聪明的观点,我明天会检查它,并将其标记为正确答案。
$ python -m cProfile string.py