python how to run process in detached mode

前端 未结 2 889
闹比i
闹比i 2020-12-15 11:09

here is a example:

from multiprocessing import Process
import time


def func():
    print(\'sub process is running\')
    time.sleep(5)
    print(\'sub proc         


        
2条回答
  •  生来不讨喜
    2020-12-15 12:02

    Following the excellent answer from @falsetru, I wrote out a quick generalization in the form of a decorator.

    import os
    from multiprocessing import Process
    
    
    def detachify(func):
        """Decorate a function so that its calls are async in a detached process.
    
        Usage
        -----
    
        .. code::
                import time
    
                @detachify
                def f(message):
                    time.sleep(5)
                    print(message)
    
                f('Async and detached!!!')
    
        """
        # create a process fork and run the function
        def forkify(*args, **kwargs):
            if os.fork() != 0:
                return
            func(*args, **kwargs)
    
        # wrapper to run the forkified function
        def wrapper(*args, **kwargs):
            proc = Process(target=lambda: forkify(*args, **kwargs))
            proc.start()
            proc.join()
            return
    
        return wrapper
    

    Usage (copied from docstring):

    import time
    
    @detachify
    def f(message):
        time.sleep(5)
        print(message)
    
    f('Async and detached!!!')
    

    Or if you like,

    def f(message):
        time.sleep(5)
        print(message)
    
    
    detachify(f)('Async and detached!!!')
    

提交回复
热议问题