Search code examples
pythonruntime-errorkeyboardinterrupt

TypeError: end must be None or a string, not KeyboardInterrupt


if i press CTRL+C it Errors TypeError: end must be None or a string, not KeyboardInterrupt
Why?

Code:

import sys
def erroring(a,b,c):
  print(end=b)
sys.excepthook = erroring
while 1:pass

Solution

  • sys.excepthook needs to be a function that accepts three arguments: the type, the exception object itself, and the traceback.

    Like John Gordon said in the comments, b, the second argument, will contain the exception itself. The reason it says TypeError: end must be None or a string, not KeyboardInterrupt is because there is a type error because end must be None or type str, and you are giving it a KeyboardInterrupt. It helps to read the exceptions because they usually tell you the issue.

    I would like to elaborate more on his comment though otherwise there would be no point in posting an answer - you should generally not be using print(end = message). Use print(message, end = "") - I don't have a source that says this is better, but a) the message is what you're printing and end is meant to be the terminator/separator defaulting to newline that goes between the content - not the content itself. b) as you see here, end, unlike the print function in general, can't take any object. You can print(x) for any x even if it's not a string, but you cannot use end = x for non-strings.

    So, the easy way to fix this is:

    def erroring(a, b, c):
        print(b, end = "")
    

    (Why do you want end = "" anyway? Also, what exactly are you trying to do?)