Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

play a sound when the exception error occurs in python

Tags:

python

I want to get some data from another website using python requests. But sometimes the server does not reply correctly.

I used try and except in my code and want to play a sound in the except block.

I have already tried the following:

import winsound

try:
    #do something
except:
    winsound.Beep(400,400)

This code does not work when I executed it. It just raises the exception.

like image 599
Amir Avatar asked Jan 22 '26 10:01

Amir


2 Answers

Make sure, that winsound really works and otherwise show us the full code.

This example uses the cross platform compatible bell character \a and works:

import sys

def bell():
    sys.stdout.write('\r\a')
    sys.stdout.flush()

def riskyFunction():
    raise Exception("I am an exception")

try:
    riskyFunction()
except Exception as e:
    bell()
    raise e
like image 95
kalehmann Avatar answered Jan 23 '26 23:01

kalehmann


For Windows

import winsound
duration = 1000  # milliseconds
freq = 440  # Hz
winsound.Beep(freq, duration)

Where freq is the frequency in Hz and the duration is in milliseconds.

On Linux and Mac

import os
duration = 1  # seconds
freq = 440  # Hz
os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))

Try this

import winsound
duration = 1000  # milliseconds
freq = 440  # Hz

def makeSound():
    winsound.Beep(freq, duration)

def makeException():
    raise Exception()

try:
    makeException()
except Exception as e:
    makeSound()
    raise e
like image 33
GOVIND DIXIT Avatar answered Jan 23 '26 23:01

GOVIND DIXIT



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!