代码之家  ›  专栏  ›  技术社区  ›  Ziqi Liu

python如何在分离模式下运行进程

  •  11
  • Ziqi Liu  · 技术社区  · 8 年前

    以下是一个示例:

    from multiprocessing import Process
    import time
    
    
    def func():
        print('sub process is running')
        time.sleep(5)
        print('sub process finished')
    
    
    if __name__ == '__main__':
        p = Process(target=func)
        p.start()
        print('done')
    

    我所期望的是,主进程将在启动子进程后立即终止。但在打印“完成”后,终端仍在等待。。。。是否有任何方法可以做到这一点,以便主进程在打印“完成”后立即退出,而不是等待子进程?我很困惑,因为我没打电话 p.join()

    2 回复  |  直到 8 年前
        1
  •  10
  •   Błażej Michalik Arkaprova Majumder    5 年前

    如果存在非- daemon process .

    通过设置, daemon 属性之前 start() 调用时,可以使进程处于守护状态。

    p = Process(target=func)
    p.daemon = True  # <-----
    p.start()
    print('done')
    

    注:不会有 sub process finished 打印的消息;因为主进程将在退出时终止子进程。这可能不是你想要的。

    您应该使用双叉:

    import os
    import time
    from multiprocessing import Process
    
    
    def func():
        if os.fork() != 0:  # <--
            return          # <--
        print('sub process is running')
        time.sleep(5)
        print('sub process finished')
    
    
    if __name__ == '__main__':
        p = Process(target=func)
        p.start()
        p.join()
        print('done')
    
        2
  •  8
  •   Nolan Conaway    7 年前

    根据@falsetru的出色回答,我以装饰师的形式写下了一个快速概括。

    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
    

    用法(从docstring复制):

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

    或者如果你愿意,

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