Python losing control of subprocess? Python losing control of subprocess? linux linux

Python losing control of subprocess?


This is just an outline- but something like this?

import oscpid = os.fork()if not cpid:    # change stdio handles etc    os.setsid() # Probably not needed    App.run()    os._exit(0)os.waitpid(cpid)# clean up here

(os.fork is *nix only)

The same idea could be implemented with subprocess in an OS agnostic way. The idea is running App.run() in a child process and then waiting for the child process to exit; regardless of how the child process died. On posix, you could also trap for SIGCHLD (Child process death). I'm not a windows guru, so if applicable and subprocess doesn't work, someone else will have to chime in here.

After App.run() is called, I'd be curious what the process tree looks like. It's possible its running an exec and taking over the python process space. If thats happening, creating a child process is the only way I can think of trapping it.


If try: App.run() finally: cleanup() doesn't work; you could try to run it in a subprocess:

import sysfrom subprocess import callrc = call([sys.executable, 'path/to/run_app.py'])cleanup()

Or if you have the code in a string you could use -c option e.g.:

rc = call([sys.executable, '-c', '''import sysprint(sys.argv)'''])

You could implement @tMC's suggestion using subprocess by adding preexec_fn=os.setsid argument (note: no ()) though I don't see how creating a process group might help here. Or you could try shell=True argument to run it in a separate shell.

You might give another try to multiprocessing:

import multiprocessing as mpif __name__=="__main__":   p = mp.Process(target=App.run)   p.start()   p.join()   cleanup()


Are you able to wrap the App.Run() in a Try/Catch?

Something like:

try:    App.Run()except (KeyboardInterrupt, SystemExit):    print "User requested an exit..."cleanup()