import traceback
try:
    compile('Hmmm, nope!', '<stdin>', 'exec')
except SyntaxError as e:
    print(''.join(traceback.format_exception_only(type(e), e)))
Get traceback information including SyntaxError from compile()