我正在尝试创建一个函数来确定 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/