0

I have a python script named "prog.py". I want to add a feature that opens a new process that watches the operation of the current script. When the script terminates, the process recognizes the termination and then invokes a certain function. Here is a pseudo-code:

while (script is active):    

    sleep(1) # check its status once a second

func()

Do you have any idea how to do it?

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183

1 Answers1

1

Is there a reason the other process needs to be launched first? Seems like you could do this more efficiently and reliably by just execing when the first process completes. For example:

import atexit
import os

atexit.register(os.execlp, 'afterexitscript.py', 'afterexitscript.py', 'arg1', 'arg2')

When the current Python process exits, it will seamlessly replace itself with your other script, which need not go to the trouble of including a polling loop. Or you could just use atexit to execute whatever func is directly in your main script and avoid a new Python launch.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • +1 for the last sentence. Just use `atexit`, and don't bother with processes unless there is a specific reason you have to. – Sven Marnach May 18 '16 at 12:45
  • The problem is with the following note in atexit documentation: " The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called." I'm looking for a solution that work in any case of script termination... – CrazySynthax May 18 '16 at 13:04
  • @CrazySynthax: In that case, it would still be simpler to have the monitor process manage the "main" process, rather than the "main" process spawning a monitor that then tries to monitor the main process in turn. The former is a dead simple use of `subprocess`, the latter involves generally non-portable OS specific process detach steps and rigmarole. – ShadowRanger May 18 '16 at 14:51