使用击键停止while循环

时间:2016-02-03 15:25:55

标签: python

完成菜鸟。我已经阅读了一些以前的问题,并试图实施建议,但没有得到它的工作。我正在编写我的第一个Python程序,并希望能够按一个键来阻止程序从CTRL + C开始运行。 (请原谅我在下面粘贴的代码中的任何缩进,因为它与IDLE中的内容不一定相同。)

x=int(input('Please Input a number... \n'))

while True:
  try:
    while x!=5:
        if x<5:
            x=x+1
            print ('Your value is now %s'%x)
            if x==5:
                print('All done, your value is 5')

        elif x>5:
            x=x-1
            print('Your value is now %s'%x)
            if x==5:
                print('All done, your value is 5')
  except KeyboardInterrupt:
      import sys
      sys.exit(0)

1 个答案:

答案 0 :(得分:1)

没有以非阻塞方式检测按键的内置方法,但可能有第三方模块可以查询您的操作系统的键盘状态。例如,Windows有Pywin32。示例实现:

import time
import win32api

def is_pressed(key):
    x = win32api.GetKeyState(key)
    return (x & (1 << 8)) != 0

print "Beginning calculation. Press the Q key to quit."
while not is_pressed(ord("Q")):
    print "calculating..."
    time.sleep(0.1)
print "Finished calculation."
相关问题