1

I've written a python script that looks up the recommended server at nordvpn.com and starts the according vpn. There is a part in this script where I assure there is internet access. When I run the script from a terminal, I cannot interrupt this loop by pressing ^C if there is no connection. How can I adapt the code so that the loop is interruptible?

Here is relevant part of the code:

#!/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....")

    # ...
maddingl
  • 197
  • 4
  • 20
  • 2
    Don't use a blanket `except`. Use `except Exception:` which will allow you to interrupt it. – roganjosh Jun 24 '18 at 06:40
  • yes, that does it! Wow, so simple! I do not understand why this is making such a difference though.... Just out of curiosity, could you explain why and how this little change is making it work? – maddingl Jun 24 '18 at 06:45
  • 1
    I'm reluctant to say this a dupe: https://stackoverflow.com/questions/18982610/difference-between-except-and-except-exception-as-e-in-python. The `as e` is not relevant for you. `except` on its own will handle every error, even KeyboardInterrupt. `except Exception` will let it slide. – roganjosh Jun 24 '18 at 06:50
  • right, thanks! If you make an answer out if this, I can accept it and this question can be seen as solved – maddingl Jun 24 '18 at 07:01

2 Answers2

2

Using except: will catch all errors, including KeyboardInterrupt. You can instead use except Exception: which will not catch SystemExit, KeyboardInterrupt and GeneratorExit. This will allow you to break a loop with Ctrl + C. You can find more information here and here.

roganjosh
  • 12,594
  • 4
  • 29
  • 46
0

this is because of your default except block which takes all Interrupts including KeyboardInterrupt which is your ^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...."