Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Format traceback

Tags:

python

The goal is to print the traceback from a failed python script. I have referenced a ton of stack articles, but I can not find one tailored to my needs. The goal is to email the traceback when there is a failure. I can email everything fine, it is just formating said traceback.

To get my traceback:

trace = traceback.format_exc()
send_email("Python Failure", trace, "[email protected]")

Email is being run through an html emailing with smtpObj and MIMEMultipart:

def send_email(subject, message, receivers):
    sender = "mydomain.com"
    msg = MIMEMultipart("alternative")
    msg["Subject"] = subject
    msg["From"] = sender
    msg["To"] = ", ".join(receivers)

    html = """
    <html>
        <head></head>
        <body>
            <p><b>""" + subject + """</b></p>
            <p>""" + message + """</p>
        </body>
    </html>
    """
    part1 = MIMEText(message, "plain")
    part2 = MIMEText(html, "html")

    msg.attach(part1)
    msg.attach(part2)

    smtpObj = smtplib.SMTP("thats.not.cheddar")
    smtpObj.sendmail(sender, receivers, msg.as_string())
    smtpObj.quit()

When I receive the email, the traceback is there but it is all on one line. I was just wondering if anyone could help format a little bit better.

like image 276
user20929302 Avatar asked Dec 06 '25 02:12

user20929302


1 Answers

Promoting @snakecharmerb's comment to an answer because it worked for me. Wrap the traceback in <pre> tags:

f"<pre>{traceback.format_exc()}</pre>"
like image 105
Noumenon Avatar answered Dec 07 '25 18:12

Noumenon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!