代码之家  ›  专栏  ›  技术社区  ›  Roshin Raphel

Python脚本没有退出,键盘中断

  •  1
  • Roshin Raphel  · 技术社区  · 4 年前

    我做了一个简单的脚本来截图,每隔几秒钟保存到一个文件中。

    from PIL import ImageGrab as ig
    import time
    from datetime import datetime
    
    try :
        while (1) :
            tm = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
            try :
                im = ig.grab()
                im.save('/home/user/tmp/' + tm + '.png')
                time.sleep(40)
            except :
                pass
    except KeyboardInterrupt:
        print("Process interrupted")
        try :
            exit(0)
        except SystemExit:
            os._exit(0)
            
    

    它工作得很好(在ubuntu18.04,python3中),但是键盘中断不起作用。我跟着 this 问题并添加了 except KeyboardInterrupt: 声明。我按的时候又拍了一张截图 CTRL+C

    2 回复  |  直到 4 年前
        1
  •  2
  •   Patrick Artner    4 年前

    你需要把你的键盘中断异常处理上移一个。键盘中断不会到达外部try/except块。

    你想逃离 while 循环,while块内的异常在这里处理:

    while True: # had to fix that, sorry :)
        tm = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
        try :
            im = ig.grab()
            im.save('/home/user/tmp/' + tm + '.png')
            time.sleep(40)
        except :   # need to catch keyboard interrupts here and break from the loop
            pass
    

        2
  •  1
  •   Abhigyan Jaiswal    4 年前

    请使用以下代码修复您的问题:

    from PIL import ImageGrab as ig
    import time
    from datetime import datetime
    
    while (1):
        tm = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
        try:
            im = ig.grab()
            im.save('/home/user/tmp/' + tm + '.png')
            time.sleep(40)
        except KeyboardInterrupt: # Breaking here so the program can end
            break
        except:
            pass
    
    print("Process interrupted")
    try:
        exit(0)
    except SystemExit:
        os._exit(0)
    
    推荐文章