4
\$\begingroup\$

I'm trying to create an alarm function with Python3. The below code does work but it doesn't seem like this is the most optimal way of achieving something like this. Is there a more pythonic way?

#!/usr/local/bin/python3
import os
import time
def alarm():
 os.system('amixer -D pulse sset Master 30%') # >> Set initial volume
 for beep in range(0, 20):
 time.sleep(.002)
 os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (.08, 2500))
alarm()
SuperBiasedMan
13.5k5 gold badges37 silver badges62 bronze badges
asked Oct 13, 2015 at 3:55
\$\endgroup\$
0

2 Answers 2

7
\$\begingroup\$
  • Pythonic approach

    For sound playback in Python, see this discussion.

  • Avoid os.system

    If you are forced to use it, supply a fully qualified path to the executable. You never know what weird program called play may be in the search path prior to an intended one.

  • Modularize

    As written, the code is not reusable. An attempt to import it would result in an immediate alarm sound. Put the call to alarm in an

    if __name__ == '__main__':
    

    clause.

  • Avoid magic numbers

    All the parameters (beep duration, volume, etc) better be passed via a command line (see sys.argv and optparse module).

  • Dummy variable

    is customarily denoted as _:

     for _ in range(20):
    
answered Oct 13, 2015 at 5:05
\$\endgroup\$
2
\$\begingroup\$

This is the old way of formatting strings:

'play --no-show-progress --null --channels 1 synth %s sine %f' % (.08, 2500)

The current Python method is to use str.format.

'play --no-show-progress --null --channels 1 synth {} sine {}'.format(.08, 2500)

It's not a huge advantage here, though you'll notice it's type agnostic. But it has many advantages available so it's good to get used to using it.

answered Oct 13, 2015 at 8:45
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.