创建一个能够识别现有代码中无限循环的函数

use*_*178 2 python infinite-loop halting-problem

我正在尝试创建一个函数来识别python文件中的代码是否会通过无限循环.这是我到目前为止:

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)
Run Code Online (Sandbox Code Playgroud)

我要做的是执行文件,并尝试计算执行的行数,并将其与前一个计数器中的任何数字进行比较.例如,如果计数器> lines_exected,则返回True,代码中存在无限循环.这会有用吗?或者我还需要尝试别的吗?

Bre*_*arn 8

这是不可能的.阅读暂停问题.

而且,即使它在理论上是可能的,或者即使你只是想做某种启发式猜测,你显然也不能通过运行文件来做到这一点.如果程序有一个无限循环,你将运行无限循环并陷入其中,所以你永远不会有机会检查你的计数器.