在下面的程序中,我在Windows 7专业版64上运行,我尝试允许用户在需要时进行干预(通过内部while
循环)并导致外部while
循环重复一个动作。否则,内部while
循环会超时,该程序将只是继续畅通无阻:在Python循环中重复超时或用户输入
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提供的解决方案中获得了它的想法。 关于如何让这个工作的任何想法?
'kbhit'和'getch'需要被连接到控制台窗口的过程。如果你使用IDLE ,那么该进程没有控制台 - 至少在使用pythonw.exe运行默认方式时,即使你使用连接的控制台运行IDLE(例如,使用Win + R运行对话框运行py-3 -m idlelib'),我怀疑你希望用户不得不切换到控制台窗口来输入输入 – eryksun
无论如何,IDLE和其他IDE shell只是开发环境,如果你打算将它作为控制台脚本,如果没有连接的控制台(例如'open(“CONIN $”)'失败),你可以模拟假的控制台I/O函数以用于测试。如果它不是sup构成一个控制台程序,然后使用GUI工具包创建自己的窗口并阅读键盘输入。 – eryksun