【问题标题】:Making a function that will identify an infinite loop in existing code制作一个将识别现有代码中的无限循环的函数
【发布时间】:2013-12-23 00:49:19
【问题描述】:

我正在尝试创建一个函数来识别 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)

我要做的是执行文件,也许尝试计算执行了多少行并将其与前一个计数器中的任何数字进行比较。例如,如果计数器>lines_exected,则返回True,代码中存在无限循环。这行得通吗?还是我必须尝试其他方法?

【问题讨论】:

  • google“停机问题”

标签: python infinite-loop halting-problem


【解决方案1】:

这是不可能的。阅读halting problem

此外,即使理论上可行,或者即使您只想进行某种启发式猜测,您显然也无法仅通过运行文件来完成。如果程序有无限循环,您将运行无限循环并陷入其中,因此您将永远没有机会检查您的计数器。

【讨论】:

  • 嗯,这只是回答了这个问题。谢谢!我会阅读这个。
【解决方案2】:

一般情况下,this simply cannot be done。您可能能够识别出某些明显是无限循环的简单案例 (while True:),并且有静态分析工具可以做到这一点,但通常没有办法做您想做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 2011-02-19
    • 2010-12-29
    • 1970-01-01
    相关资源
    最近更新 更多