2013-04-15 6 views
7

Ich versuche, das cProfile Modul in Python 3.3.0, zu importieren, aber ich habe den folgenden Fehler:Kann nicht cProfile in Python importieren 3

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' 

Der vollständige Code (cProfile_try.py) wird wie folgt

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)') 
+2

Do Sie haben ein 'cProfile.py' im aktuellen Verzeichnis oder sonst Wo auf 'sys.path' wird vor der Standardbibliothek gesucht? Drucken Sie den Wert von 'cProfile .__ file__'. – eryksun

+0

@eryksun: Ich denke, cProfile ist ein Modul in der Sitzung importiert werden, richtig? Nach dem Import sollte 'cProfile.run' verfügbar sein ... – alittleboy

+0

@eryksun: thanks! Ich habe dieses '/ System/Bibliothek/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cProfile.py' als die Ausgabe 'print (cProfile .__ Datei __)'. – alittleboy

Antwort

8

Wie in einem Kommentar erwähnt, ist es wahrscheinlich, dass dort unerwartet eine Datei mit dem Namen profile.py möglicherweise im aktuellen Verzeichnis vorhanden ist. Diese Datei wird unbeabsichtigt von cProfile verwendet, wodurch Pythons profile Modul verdeckt wird.

Ein vorgeschlagene Lösung ist:

mv profile.py profile_action.py 

nächste für eine gute Maßnahme,

Bei der Verwendung von Python 3:

rm __pycache__/profile.*.pyc 

Wenn Python mit 2:

rm profile.pyc