3
\$\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()
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Codereview, Kryptos. \$\endgroup\$
    – Legato
    Oct 13, 2015 at 4:07

2 Answers 2

6
\$\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):
    
\$\endgroup\$
0
\$\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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.