在我在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重复)不起作用,我不知道原因。我从提供的解决方案here中提出了自己的想法。 有关如何使其发挥作用的任何想法?
答案 0 :(得分:1)
您比较变量决策和字符串&#34;重复&#34;在您的内循环中,因为您正在使用==运算符。您应该使用=来为变量赋值:
decision = 'repeat'
答案 1 :(得分:0)
我现在设法解决了这个问题。 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')