我有一个使用subprocess.call()
来调用linux程序的for循环。有时它需要太长时间,我希望能够跳到continue
循环。在s
正在运行时,我是否有办法观看键盘输入(例如subprocess.call()
)?
for x in y:
if lookforkeyboardinput = s:
continue
subprocess.call(['program', x])
像这样。
答案 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