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

Question:

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.

try:
    fileInpath = sys.stdin.read()#возвращает строку
    if not(fileInpath):
        print('\nОтсутствует входящий файл')
        myParser.print_help()
        sys.exit()  
except KeyboardInterrupt:
    sys.exit()

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

prog.py -i

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

type E | prog.py

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?

Answer:

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

When input is provided via type E | then sys.stdin.read() 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 sys.stdin.read() , 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
AllEscort