Skip to content
Advertisement

Pycharm’s “stop” does not run finally code

I am running a python project in pycharm. In the code we have a main “try-catch-finally” block e.g.

try:
   # Some stuff like opening files and video streams
except SomePossibleExceptions:
   # Handle possible exception
finally:
   # Save, close and tidy up unfinished files / videos / output streams

If I run the program in the terminal it will reach the finally block when I press our quit button or “ctrl-c” and perform the post processing required. However, after pressing “stop” when using the run tool in PyCharm it just quits and does not reach the finally block.

The obvious answer is to just run in the terminal but is there a way to get PyCharm to run the finally block after pressing “stop” in the run tool?

Advertisement

Answer

No, using the red stop button terminates the process immediately.

I think you alluded to this, but the only workaround I have found is to edit the run configuration:

run > edit configurations > tick the box for ‘Emulate terminal in output console’ or ‘Run with Python Console’.

With either of those selections ticked, the run window will accept ctrl-C inputs which will allow your finally block to execute.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement