Frage

I'm trying to create a function that will identify if the code in a python file will go through and infinite loop or not. This is what I have so far:

def reader(filename):
    myfile = open(filename)
    counter = 0 
    #counters the number of lines in the file
    for line in myfile:
        counter +=1
        print line
    #print number of lines in file    
    print counter

    #execute the code in file        
    execution = execfile(filename)

What I'm trying to do is execute the file, and maybe try to count how many lines are executed and compare that to whatever number in the previous counter. For example, if the counter > lines_exected, then return True, there is an infinite loop in code. Would this work? Or would I have to try something else?

War es hilfreich?

Lösung

This is impossible. Read up on the halting problem.

Also, even if it were possible in theory, or even if you just want to do some sort of heuristic guess, you obviously can't do it by just running the file. If the program has an infinite loop, you will run the infinite loop and get stuck in it, so you'll never get a chance to check your counter.

Andere Tipps

In the general case, this simply cannot be done. You may be able to identify certain simple cases that are obviously infinite loops (while True:), and there are static analysis tools which do so, but in general there is no way to do what you're trying to do.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top