如何使unix的^ C中断python循环?

时间:2018-06-24 06:40:20

标签: python unix sigint

我编写了一个python脚本,该脚本在nordvpn.com上查找推荐的服务器并启动相应的vpn。我保证该脚本中的一部分可以访问互联网。从终端运行脚本时,如果没有连接,则无法通过按^ C中断此循环。如何修改代码以使循环可中断?

这是代码的相关部分:

#!/usr/bin/env python3

import re
import os
from selenium import webdriver

if __name__ == '__main__':

    # ...

    # wait for internet connection and load geckodriver
    while True:
        try:
            browser = webdriver.Firefox(
                executable_path=r'/home/maddin/bin/.vpn/geckodriver',
                log_path='/dev/null')
            break
        except:
            print("not connected yet, trying again....")

    # ...

2 个答案:

答案 0 :(得分:2)

使用except:将捕获所有错误,包括KeyboardInterrupt。您可以改用except Exception:来捕获SystemExitKeyboardInterruptGeneratorExit。这将允许您使用Ctrl + C中断循环。您可以找到更多信息herehere

答案 1 :(得分:0)

这是因为您的默认except块会占用所有中断,包括KeyboardInterrupt是您的 ^ C

while True:
    try:
        browser = webdriver.Firefox(
            executable_path=r'/home/maddin/bin/.vpn/geckodriver',
            log_path='/dev/null')
        break
    except KeyboardInterrupt:
        # do whatever you want to do on ^C
    except:
        print("not connected yet, trying again...."