Search code examples
pythonexception

How can I set up an alert or beeping sound when my code breaks? (In Python ideally)


I am running some code for a robot, and it will keep running until I manually kill the process. OR if the code unexpectedly hits an error like a syntax error or other such errors/exceptions and crashes out.

I was wondering if it is possible to set up some alerting or beeping noise when my code crashes out.

My aim is to look away from my screen and only check it if the process has stopped running. If there are any other common ways to achieve the above, that would be great!

I can set up a beeping noise using python libraries, but the challenge is to get it executing, when the code breaks out unexpectedly.


Solution

  • First of all I would wrap your code into a main function if it isn't already, for neatness and other reasons I won't get into here. Then on your

    if __name__ == '__main__':
       main()
    

    statement before you start the program do this:

    try:
       main()
    except Exception as e:
       do_bleep()
       raise e
    

    This way you get your bleeping sound and then still get the exception like normal