Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a process and quit without waiting for it

Tags:

python

windows

In Python under Windows: I want to run some code in a separate process. And I don't want the parent waiting for it to end. Tried this:

from multiprocessing import Process
from time import sleep

def count_sheeps(number):
    """Count all them sheeps."""
    for sheep in range(number):
        sleep(1)

if __name__ == "__main__":
    p = Process(target=count_sheeps, args=(5,))
    p.start()
    print("Let's just forget about it and quit here and now.")
    exit()

which starts the child process and continues executing. However, when the parent reaches the end, it still waits for the child to exit.

Is there a way of letting the parent quit even when the child is running? Sure, I could just run a new python interpreter using subprocess.Popen and feed to it the sheep-counting as a separate script.

Still, there's this whole module for playing with processes of Python code, so I'd like to take advantage of that instead of hacking on the OS. Also, it would be awesome if the same code worked everywhere where Python does, not just on Windows.

like image 513
Tomas Sedovic Avatar asked Nov 11 '09 23:11

Tomas Sedovic


1 Answers

Here is a dirty hack if you must make it work with Process. Basically you just need to overwrite join so that when it does get called before the script exists it does nothing rather than block.


from multiprocessing import Process
import time
import os


def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())


def f(name):
    info('function f')
    time.sleep(3)
    print('hello', name)


class EverLastingProcess(Process):
    def join(self, *args, **kwargs):
        pass

    def __del__(self):
        pass


if __name__ == '__main__':
    info('main line')
    p = EverLastingProcess(target=f, args=('bob',), daemon=False)
    p.start()


like image 198
derchambers Avatar answered Sep 29 '22 06:09

derchambers