【问题标题】:How do you continue a for loop with a keyboard input in python?如何在 python 中使用键盘输入继续 for 循环?
【发布时间】:2014-10-12 19:30:40
【问题描述】:

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

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

类似的东西。

【问题讨论】:

    标签: python linux io


    【解决方案1】:

    使用键盘中断异常:

    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
    

    【讨论】:

    • 这会导致程序无法通过 ctrl+c 退出。如何将密钥设置为 s
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    相关资源
    最近更新 更多