python - 制作一个函数来识别现有代码中的无限循环

标签 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)

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

最佳答案

这是不可能的。阅读 halting problem .

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

关于python - 制作一个函数来识别现有代码中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20735680/

相关文章:

python - FFmpeg/python - 从 shell 运行时命令有效,但从 python 运行时失败

c# - 如何检测到 StackOverflowException?

c++ - 使用 std::thread 时,主线程中的 while 循环卡住了

javascript - 使用键盘按下打破 JS 中的无限循环

javascript - meteor -检测无限循环

computer-science - 自动计算终止算法的算法时间复杂度

haskell - 'try' 可以决定程序何时停止

python - 重命名内置的 python 方法,如 replace()

python - 基于默认值列替换多列中的 NaN 的最有效方法是什么?

database - Django模型/SQLAlchemy肿!有没有真正的Pythonic数据库模型?