2011-05-04 15 views
5

usando Python 2.7 me sale este error:AttributeError: Objeto de 'módulo' no tiene ningún atributo 'maketrans' mientras se ejecuta cprofile

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' 

mientras se ejecuta este código simple:

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

utilizando esta llamada:

$ python -m cProfile string.py 

estoy usando Ubuntu Natty Narwhal, e instalado el paquete python-profiler (no sé si esto es nece sary).

Respuesta

7

A medida que el Python tutorial on modules explica:

Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation- dependent default. This allows Python programs that know what they’re doing to modify or replace the module search path. Note that because the directory containing the script being run is on the search path, it is important that the script not have the same name as a standard module, or Python will attempt to load the script as a module when that module is imported.

textwrap hace import string. Su secuencia de comandos se llama string.py y viene primero (o al menos antes de los directorios stdlib) en la ruta de búsqueda, por lo que se importa. Pero no define las funciones y las constantes esperadas, p. no tiene un módulo maketrans. Eso es lo que te dice el error.

(El mismo error debe ocurrir si sólo ejecuta el script sin perfiles.)

+8

Moraleja de la historia: Nunca el nombre de su programa de la misma como un módulo stdlib. – jathanism

+0

Guau, ese es un punto inteligente, lo revisaré mañana y lo marcaré como la respuesta correcta. – Doppelganger

Cuestiones relacionadas