Reputation: 6147
I'm seeing a lot of the following pattern in a codebase I'm checking out at the moment:
try:
import moduleA
import moduleB
from custom.module.A import AX
from custom.module.A import AY
except KeyboardInterrupt:
sys.exit()
Haven't seen it before. What's this guarding against?
Upvotes: 0
Views: 100
Reputation: 142106
The only way I can think of that makes sense is if some of those modules
for some reason have input
/raw_input
that run inside of them, or otherwise deliberately raise KeyboardInterrupt
for some reason.
Otherwise, really not quite sure what it's meant to do... (unless some of the imports take hours to run, and if you get fed up, can abandon it without seeing a traceback - but that doesn't make much sense either)
Upvotes: 3
Reputation: 2641
Whenever you press ctrl+C from your keyboard, a KeyboardInterrupt is sent to the python process. If not caught, it will cause an exception in the code so that the code exits wherever it is currently. In this case, there is no special action being taken, but, just a call to sys.exit()
, which again causes the program to exit, but, without displaying the stack traceback
From the documentation:
Upvotes: 2
Reputation: 52853
It's not guarding against anything, at least not obviously. It's catching a KeyboardInterrupt:
Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.
Then simply exiting, which is what an interrupt would do anyway.
Upvotes: 1