2

I wrote a simple python script that backups a certain folder when I run it. Now I want to make it run whenever I close a certain application (that I didn't code). How would I go about doing that?

J. C.
  • 109
  • 2
  • 11
  • 1
    That's kind of tricky.. You may have to lookup the entire process list of the computer, and look for the application you need, once found, repeat the process until it is not there, and then run your code. also save the actual PID of the process so if there's multiple instances of the app running you'll have no problems. – Pablo Recalde Feb 11 '17 at 09:37
  • Well that sounds a little bit too hard for a beginner like me. I think I'll just run it manually for now... – J. C. Feb 11 '17 at 09:47

2 Answers2

2

Suppose you want to backup a folder when firefox browser exits.
Using ps -A | grep firefox we can see whether such process exists or not. It's a little bit hacky but you could write a Python script to check whether such process exists every timeout seconds and if it existed before and doesn't exists anymore, we know that it has been closed so we can do our backup. Then run that loop forever on your OS start-up to watch the process status.

import subprocess
import time


process_name = 'firefox'
cmd = "ps -A | grep {}".format(process_name)
timeout = 3
process_exists = False


while True:
    ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ps.communicate()[0]

    if output:  # Process is open
        process_exists = True
        print('Process is open so we continue the loop')
        time.sleep(timeout)

    elif process_exists and not output:
        # If process existed before and now there is no output, it means that it has been closed
        # So we backup our folder now
        print('backup data here')
        process_exists = False

    else:
        print('Process has not started yet')
        time.sleep(timeout)

Use these answers to run this script at your start-up

Community
  • 1
  • 1
Amin Etesamian
  • 3,363
  • 5
  • 27
  • 50
1

The answer might not be in Python but in your shell. Supposing bash as a shell, firefox as the third-party program and myscript.py as an executable python script:

[prompt]$ firefox && myscript.py

When firefox ends successfully, myscript.py is run. You can wrap this in a launcher script.

Instead of && you can use || to run myscript.py if firefox ended in an error. Or ; to run the script no matter how firefox ended.

This solution involves no polling.

daragua
  • 1,133
  • 6
  • 8