Run a process and quit without waiting for it

后端 未结 5 1391
-上瘾入骨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:21

    You can declare the process as daemon with p.daemon = True. As http://docs.python.org/2/library/threading.html#thread-objects says: "The significance of this flag is that the entire Python program exits when only daemon threads are left."

    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.daemon = True
        p.start()
        print("Let's just forget about it and quit here and now.")
        exit()
    

提交回复
热议问题