[英]Timeout or User Input to Repeat in Python Loops
在下面的程序中,我在 Windows 7 Professional 64 上运行,我试图允许用户在需要时进行干预(通过内部while
循环)并导致外部while
循环重复操作。 否则,内部while
循环将超时,程序将继续畅通无阻:
import msvcrt
import time
decision = 'do not repeat' # default setting
for f in ['f1', 'f2', 'f3']:
print ('doing some prepartory actions on f')
while True: # outer while loop to allow repeating actions on f
print ('doing some more actions on f')
t0 = time.time()
while time.time() - t0 < 10: # inner while loop to allow user to intervene
if msvcrt.kbhit(): # and repeat actions by pressing ENTER if
if msvcrt.getch() == '\r': # needed or allow timeout continuation
decision = "repeat"
break
else:
break
time.sleep(0.1)
if decision == "repeat":
print ("Repeating f in the outer while loop...")
continue
else:
break
print ('doing final actions on f in the for loop')
但是,内循环的用户输入部分(按 ENTER 重复)不起作用,我不知道为什么。 我从这里提供的解决方案中汲取了它的想法。 关于如何让它发挥作用的任何想法?
由于您使用 == 运算符,因此您正在内部循环中比较变量决策和字符串“重复”。 您应该使用 = 来为变量赋值:
decision = 'repeat'
我现在已经设法解决了这个问题。 kbhit
进程在我使用的 IDLE(Wing IDE)中不起作用,但如果从命令提示符调用它可以工作(正如 @eryksun 所说,这可能适用于所有 IDLE 而不仅仅是 Wing)。 我发现的另一个问题是getch()
进程没有执行我需要的操作,我必须使用返回 unicode 的getwch()
。 再做一个小调整(默认decision
为decision = 'Reset decision to not repeat'
,代码现在处于良好的工作状态:
import msvcrt
import time
decision = 'do not repeat' # default setting
for f in ['f1', 'f2', 'f3']:
print ('doing some prepartory actions on f')
while True: # outer while loop to allow repeating actions on f
print ('doing some more actions on f')
t0 = time.time()
while time.time() - t0 < 10: # inner while loop to allow user to intervene
if msvcrt.kbhit(): # and repeat actions by pressing ENTER if
if msvcrt.getchw() == '\r': # needed or allow timeout continuation
decision = "repeat"
break
else:
break
time.sleep(0.5)
if decision == "repeat":
print ("Repeating f in the outer while loop...")
decision = 'Reset decision to not repeat'
continue
else:
break
print ('doing final actions on f in the for loop')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.