Run a process and quit without waiting for it

后端 未结 5 1390
-上瘾入骨i
-上瘾入骨i 2021-02-20 11:36

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 impo         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-20 12:14

    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()
    
    
    

提交回复
热议问题