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?
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.