如何在python中使用键盘输入继续for循环?

时间:2014-10-12 19:30:41

标签: python linux io

我有一个使用subprocess.call()来调用linux程序的for循环。有时它需要太长时间,我希望能够跳到continue循环。在s正在运行时,我是否有办法观看键盘输入(例如subprocess.call())?

for x in y:
    if lookforkeyboardinput = s:
        continue
    subprocess.call(['program', x])

像这样。

1 个答案:

答案 0 :(得分:2)

使用键盘中断异常:

for x in y:
    try:
        subprocess.call(['program', x])
    except (KeyboardInterrupt, SystemExit):
        continue

示例:

from time import sleep

for x in range(0, 5):
    try:
        sleep(5)
        print x
    except (KeyboardInterrupt, SystemExit):
        continue

输出:

hedde-mpb:Desktop hedde$ python test.py 
1 
^C  // pressed right after 1 appears, slightly over 5 seconds later 3 appears
3