Bug fix for formatPythonException()

This one was pretty heinous, so I though it was worth submitting immediately rather than waiting to include it with the work I'm currently on. The first commit is the important fix - the latter one turned out to be unrelated, but since I'd done it during the course of investigation I thought it was worth including anyway.