我编写了一个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....")
# ...
答案 0 :(得分:2)
使用except:
将捕获所有错误,包括KeyboardInterrupt
。您可以改用except Exception:
来捕获SystemExit
,KeyboardInterrupt
和GeneratorExit
。这将允许您使用Ctrl + C中断循环。您可以找到更多信息here和here。
答案 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...."