2011-05-04 37 views
5

Sử dụng python 2.7 Tôi nhận được lỗi này:AttributeError: đối tượng 'module' không có thuộc tính 'maketrans' trong khi chạy 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' 

khi chạy mã đơn giản này:

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

sử dụng cuộc gọi này:

$ python -m cProfile string.py 

Tôi đang sử dụng Ubuntu Natty Narwhal và cài đặt gói python-profiler (Tôi không biết nếu đây là phân sary).

Trả lời

7

Khi Python tutorial on modules giải thích:

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 không import string. Tập lệnh của bạn có tên là string.py và đến trước (hoặc ít nhất là trước các thư mục stdlib) trên đường dẫn tìm kiếm, vì vậy nó được nhập. Nhưng nó không xác định các hàm và hằng số được mong đợi, ví dụ: nó không có mô-đun maketrans. Đó là những gì lỗi cho bạn biết.

(Các lỗi tương tự sẽ xảy ra nếu bạn chỉ chạy các kịch bản mà không cần hồ sơ.)

+8

đạo đức của câu chuyện: Không bao giờ đặt tên cho chương trình của bạn giống như một module stdlib. – jathanism

+0

Wow, đó là một điểm thông minh, tôi sẽ kiểm tra nó vào ngày mai và đánh dấu đây là câu trả lời đúng. – Doppelganger

Các vấn đề liên quan