简体   繁体   English

我想在不停止任何功能的情况下中断python中的循环

[英]interrupting a loop in python without stopping a function whenever I want

Before I get to the point, here is my sample code: 在此之前,这里是我的示例代码:

x = 0
while x < 50000000:
    x += 1
    print(x)

print("Calculation done")    

As you can see, this code will run for a long period of time. 如您所见,此代码将运行很长时间。 I want to interrupt this 'while loop' without arising any error and get the last print "Calculation done" 我想中断此“ while循环”而不会出现任何错误,并获得最后的打印结果“计算完成”

Is there any way for it? 有什么办法吗?

Thanks 谢谢

You could wrap your loop in a try-except : 您可以将循环包装在try-except

try:
    x = 0
    while x < 50000000:
        x += 1
        print(x)
except KeyboardInterrupt:
    pass
print("Calculation done")    

Edit: you would stop this with ^C 编辑:您可以使用^C停止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM