Search code examples
pythonlinuxshellscriptingxbmc

Toggle process with Python-script (kill when running, start when not running)


I'm currently running an OpenELEC (XBMC) installation on a Raspberry Pi and installed a tool named "Hyperion" which takes care of the connected Ambilight. I'm a total noob when it comes to Python-programming, so here's my question:

How can I run a script that checks if a process with a specific string in its name is running and:

  • kill the process when it's running
  • start the process when it's not running

The goal of this is to have one script that toggles the Ambilight. Any idea how to achieve this?


Solution

  • You may want to have a look at the subprocess module which can run shell commands from Python. For instance, have a look at this answer. You can then get the stdout from the shell command to a variable. I suspect you are going to need the pidof shell command.

    The basic idea would be along the lines of:

    import subprocess
    
    try:
        subprocess.check_output(["pidof", "-s", "-x", "hyperiond"])
    except subprocess.CalledProcessError:
        # spawn the process using a shell command with subprocess.Popen
        subprocess.Popen("hyperiond")
    else:
        # kill the process using a shell command with subprocess.call
        subprocess.call("kill %s" % output)
    

    I've tested this code in Ubuntu with bash as the process and it works as expected. In your comments you note that you are getting file not found errors. You can try putting the complete path to pidof in your check_output call. This can be found using which pidof from the terminal. The code for my system would then become

        subprocess.check_output(["/bin/pidof", "-s", "-x", "hyperiond"])
    

    Your path may differ. On windows adding shell=True to the check_output arguments fixes this issue but I don't think this is relevant for Linux.