maligree
maligree

Reputation: 6147

Try-surrounded imports and catching KeyboardInterrupt

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

Answers (3)

Jon Clements
Jon Clements

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

GodMan
GodMan

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:

http://docs.python.org/2/library/exceptions.html?highlight=keyboardinterrupt#exceptions.KeyboardInterrupt

Upvotes: 2

Ben
Ben

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

Related Questions