Search code examples
pythonpython-3.xlinuxbackground-process

How to trigger a function when a certain application launches in Python


Assuming a python script running in the background, how can I trigger a function inside the script when I launched a certain application/software on my computer (Linux).

I googled a lot about this, but couldn't find a solution!

Thank you in advance.


Solution

  • Assume, you have to call function callemnow when an external process "abc" has started. There are multiple ways of doing it but below is a sample code which would be easy for you to understand.

    Note: ps -eaf | grep will give process details. The same command you can call from python script vi subprocess.

    while True is just for the convenience. You have to substitute that statement as per your logic flow

    from subprocess import Popen, PIPE
    
    def externalprocess():
        cmd = Popen(['ps', '-eaf'],stdout=PIPE)
        (output, err) = cmd.communicate()
        return True if "abs" in output else False
    
    def callmenow()
        '''
        your logic
        '''
    
    if __name__ == '__main':
        while True:
            if externalprocess():
                callmenow()