python – Why is the except KeyboardInterrupt executed before myParser.print_help ()?


Below is an excerpt from my code. The program is not always provided with a file on stdin , and after Ctrl + C it should not spit out any traces, just exit cleanly, print and a help message from the parser to the console.

    fileInpath =возвращает строку
    if not(fileInpath):
        print('\nОтсутствует входящий файл')
except KeyboardInterrupt:

The program now only does print and exits without errors if I enter into the console -i

That is, fileInpath is None , stdin got nothing. BUT! When I type to the console:

type E |

I have both print and help from the parser.

Question: why is e xcept KeyboardInterrupt executed before myParser.print_help() ? And how to make help appear in the first case, as well as in the second?


When you press Ctrl + C then in python it throws KeyboardInterrupt exception by default.

When input is provided via type E | then reads all the input and returns: you probably don't have time to hit Ctrl + C , so both print() and myParser.print_help() are executed.

If you press Ctrl + C while the code is hanging on , then the code jumps into the except KeyboardInterrupt block: all intermediate lines are NOT executed, that is, print() and myParser.print_help() not executed at all (not earlier , not later than).

Scroll to Top