0

I am doing some Python tutorials to try and learn as much as possible about the language and I am having some problems with exception handling. I am running the code in cmd in Windows 10 using Python 3.4.3. Specifically, the KeyboardInterrupt block does not print anything at all when Ctrl + C is pressed. While that is not necessarily important, I'm thinking of times when I might need to perform other actions upon a KeyboardInterrupt such as writing out to a file.

def process_input(input_value):
    try:
        float_value = float(input_value)
    except ValueError:
        raise ValueError("\n'%s' is not a number." % input_value)

    if float_value <= 0:
        raise ValueError("\nMeasurements must be positive values.")

    return float_value


def get_dims(*names):
    dims = []

    for n in names:
        raw_input = input("Please enter a %s : " % n)
        processed_input = process_input(raw_input)
        dims.append(processed_input)

    return dims


def main():
    print("\nThis program will request a length, width, and height and\n will" \
     "return the total volume for a box.\n")

    success = False
    try:
        length, width, height = get_dims('Length', 'Width', 'Height')
        success = True
    except ValueError as e:
        print(e)
    except KeyboardInterrupt:
        print("\nInterrupted.")

    if success:
        volume = length * width * height
        print("\nThe volume of the box is %.2f" % volume)

if __name__ == '__main__':
    main()

Instead of printing out the message "Interrupted", when pressing Ctrl + C during the first user input, the output looks like this: Please enter a Length : Traceback (most recent call last):

I am in Windows 10, running the code in cmd. Any ideas?

Java Guru
  • 466
  • 4
  • 12
smkarber
  • 577
  • 5
  • 18
  • What is your entire output? – xrisk Feb 07 '16 at 13:59
  • Cannot reproduce, works as intended for me. – xrisk Feb 07 '16 at 13:59
  • May be relevant - http://stackoverflow.com/questions/4606942/why-cant-i-handle-a-keyboardinterrupt-in-python – xrisk Feb 07 '16 at 14:02
  • I’ve closed this as a duplicate of [this question](http://stackoverflow.com/q/31127652/216074); while that question starts from a different situation, it boils down to the same cause which is that there is a `EOFError` thrown when you CTRL-C `input()` which causes the stack trace you see, which is *then* interrupted by the `KeyboardInterrupt`. The “solution” would be to try/except the `EOFError` and wait for a bit. – poke Feb 07 '16 at 14:06
  • Ugh. I apologize. I read through 5 or 6 KeyboardInterrupt questions and never saw that one. The other ones did not satisfy my issue, but that one definitely did. Thanks! – smkarber Feb 07 '16 at 14:16
  • No need to apologize, it’s definitely a weird issue, and to be honest, that question isn’t so easy to find. But I’m glad it helped you! :) – poke Feb 07 '16 at 16:06

0 Answers0