DEV Community

Cover image for Implement --pdb in a python cli
Waylon Walker
Waylon Walker

Posted on • Originally published at waylonwalker.com

3 1

Implement --pdb in a python cli

Adding a --pdb flag to your applications can make them much easier for those using it to debug your application, especially if your applicatoin is a cli application where the user has much fewer options to start this for themselves. To add a pdb flag --pdb to your applications you will need to wrap your function call in a try/except, and start a post_mortem debugger. I give credit to this stack overflow post for helping me figure this out.

import pdb, traceback, sys


def bombs():
    a = []
    print(a[0])


if __name__ == "__main__":
    if "--pdb" in sys.argv:
        try:
            bombs()
        except:
            extype, value, tb = sys.exc_info()
            traceback.print_exc()
            pdb.post_mortem(tb)
    else:
        bombs()
Enter fullscreen mode Exit fullscreen mode

Using --pdb

python yourfile.py --pdb
Enter fullscreen mode Exit fullscreen mode

running this example with and without --pdb flag


This is day 22 of posting tils, These are bite sized pieces that help me cement in what I have learned thoughout the day. eventually they will make their way into larger form pieces.


Discuss

What do you think about --pdb do you like when cli's give you this option? Has it saved your bacon?

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay