Last active
March 28, 2020 11:47
-
-
Save yulkang/14da861b271576a9eb1fa0f905351b97 to your computer and use it in GitHub Desktop.
Test whether the exception is Ctrl + C in Pycharm's Python console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
You can use PyCharm's Python console and use Ctrl + C, | |
if you catch the exception that PyCharm raises when Ctrl + C is pressed. | |
I wrote a short function below called `is_keyboard_interrupt` | |
that tells you whether the exception is KeyboardInterrupt, | |
including PyCharm's. | |
If it is not, simply re-raise it. | |
I paste a simplified version of the code below. | |
When it is run: | |
- type 'help' and press Enter to repeat the loop. | |
- type anything else and press Enter to check that ValueError is handled properly. | |
- Press Ctrl + C to check that KeyboardInterrupt is caught, including in PyCharm's python console. | |
Note: This doesn't work with PyCharm's debugger console | |
(the one invoked by "Debug" rather than "Run"), | |
but there the need for Ctrl + C is less, | |
because you can simply press the pause button. | |
See this answer & the original question | |
on Stack Overflow: https://stackoverflow.com/a/60900672/2565317 | |
""" | |
def is_keyboard_interrupt(exception): | |
# The second condition is necessary for it to work with the stop button | |
# in PyCharm Python console. | |
return (type(exception) is KeyboardInterrupt | |
or type(exception).__name__ == 'KeyboardInterruptException') | |
if __name__ == '__main__': | |
try: | |
def print_help(): | |
print("To exit type exit or Ctrl + c can be used at any time") | |
print_help() | |
while True: | |
task = input("What do you want to do? Type \"help\" for help:- ") | |
if task == 'help': | |
print_help() | |
else: | |
print("Invalid input.") | |
# to check that ValueError is handled separately | |
raise ValueError() | |
except Exception as ex: | |
try: | |
# Catch all exceptions and test if it is KeyboardInterrupt, native or | |
# PyCharm's. | |
print('Exception type: %s' % type(ex).__name__) | |
if not is_keyboard_interrupt(ex): | |
print('Not KeyboardInterrupt!') | |
raise ex | |
print('KeyboardInterrupt caught as expected.') | |
exit() | |
except ValueError: | |
print('ValueError!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment