Python 使用用户输入打破嵌套循环
有没有一种有效的方法可以让用户在他们想要中断的特定时间(例如按键)简单地提供输入,从而中断嵌套循环?我在循环本身中有条件语句,可以用来中断循环,但是如果我只是想在任何时候停止循环,但仍然想运行其余的代码,有没有一种简单的方法可以做到这一点?为了澄清动机,我想做如下工作:Python 使用用户输入打破嵌套循环,python,python-2.7,user-interface,nested-loops,Python,Python 2.7,User Interface,Nested Loops,有没有一种有效的方法可以让用户在他们想要中断的特定时间(例如按键)简单地提供输入,从而中断嵌套循环?我在循环本身中有条件语句,可以用来中断循环,但是如果我只是想在任何时候停止循环,但仍然想运行其余的代码,有没有一种简单的方法可以做到这一点?为了澄清动机,我想做如下工作: for x in xrange(1000): for y in xrange(1000): for z in xrange(1000): print x,y,z #function
for x in xrange(1000):
for y in xrange(1000):
for z in xrange(1000):
print x,y,z #function of loop
if (user_has_pressed_key) == True: #a user input that
#can come at any time
#but there should NOT be
#a prompt needed for each iteration to run
break
else:
continue
break
else:
continue
break
我考虑过使用原始输入,但不希望循环等待用户的每次迭代,因为将有无数次迭代。似乎有一些,但即使是这些似乎只是特定于Windows的。我在多台计算机上运行这段代码,所以我希望它能在不同的操作系统上运行 如果用户按下Ctrl+C键,您可以中断嵌套循环,因为它会引发
键盘中断
异常:
try:
for x in xrange(1000):
for y in xrange(1000):
for z in xrange(1000):
print x,y,z #function of loop
except KeyboardInterrupt:
print("Stopped nested loops")
如果用户发出Ctrl+C键击,则可以中断嵌套循环,因为它会引发
键盘中断
异常:
try:
for x in xrange(1000):
for y in xrange(1000):
for z in xrange(1000):
print x,y,z #function of loop
except KeyboardInterrupt:
print("Stopped nested loops")
如果希望在用户按下任何键时循环中断,则可以尝试此导入:
from msvcrt import getch
while True:
key = getch()
if (key is not None):
break
如果希望在用户按下任何键时循环中断,则可以尝试此导入:
from msvcrt import getch
while True:
key = getch()
if (key is not None):
break
您可能需要查看异步事件的标准
信号
库。请提供最低工作示例您可能需要查看异步事件的标准信号
库。请提供最低工作示例这基本上就是我要查找的。但是出于好奇,有没有一种方法可以在没有try/except语句的情况下实现类似的方法呢。但是出于好奇,有没有一种方法可以在不使用try/except语句的情况下实现类似的方法?