pythonraspberry-piamixer

amixer: invalid command


I am trying to change the volume of my RaspberryPi using this small code snippet:

import os

def setVolume(vol,prefix):
    cmd = "amixer -q -M set PCM " + vol + "%"
    print(prefix+"Changing volume to " + vol + "%")
    print(prefix+str(os.system(cmd)))

I am using this function in two different python scripts but it works in only one of them. (this function is just for testing please ignore the prefix and stuff). It works only in one of them and it gives the error message: amixer: Invalid command! (Python 2.7.13)


Solution

  • This should be very easy for you to narrow down, as the problem ultimately has little to do with Python. Your python code is just constructing a command string that is then executed by the operating system.

    First of all, I'd suggest printing or logging the full command you are executing so that you know just what system call you're making. Your problem could very well have to do with the current working directory that's in effect when you run your command. So I'd call os.system("pwd") prior to calling your actual cmd. This will show you what the current working directory is at the time that your command is run. Then here's the modified version of your code that I suggest you run to troubleshoot:

    def setVolume(vol,prefix):
        cmd = "amixer -q -M set PCM " + vol + "%"
        print(prefix+"Changing volume to " + vol + "%")
        os.system("cmd")
        print("Executing command: >" + cmd + "<")
        print(prefix+str(os.system(cmd)))
    

    Putting '>' and '<' in there will make sure you see any whitespace in your command. Often, just doing this will show you what your problem is, as you'll notice a problem in the way you've constructed your command. In your case, it is the vol parameter that would be the interesting factor here.

    Once you have the exact command you're passing to os.system(), try running that command at a shell prompt via copy/paste. Ideally, you can do this at the same shell prompt you were using to run your Python script. "cd" into the directory indicated by your code making the "pwd" call before you try to run the command. This should isolate the problem way from Python. Hopefully you'll see matching pass/fail behavior and you can troubleshoot at the level of the system command rather than in your code. Only when you fully understand how the system call works, and just what it has to look like, would you return to Python.

    If that doesn't get you to the goal, I'd suggest using the subprocess module rather than os.system(), assuming that's available on your RasPi version of Python. I've heard of problems being solved in the past simply by switching away from os.system(), although I don't know the details.