我有一个 for 循环,它使用 subprocess.call()
来调用 Linux 程序。有时需要太长时间,我希望能够跳到继续
循环。有没有办法在 subprocess.call()
运行时监视键盘输入(例如 s
)?
for x in y:
if lookforkeyboardinput = s:
continue
subprocess.call(['program', x])
类似这样的事情。
最佳答案
使用键盘中断异常:
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
关于python - 如何在 python 中通过键盘输入继续 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26329121/