Python-多进程守护程序

14

我正在创建一个多进程,用于创建CSV文件。当我使用d.daemon = False运行代码时,它能正常工作,即在同一文件夹中创建文件。但是当使用d.daemon = True编译并运行时,它就不起作用了,也就是说不会创建文件。为什么呢?

我的代码

我有一个种子URL列表,需要从中爬取数据。

for url in config.SEED_LIST:
    # starting a new process for each category.
    d = multiprocessing.Process(target=workers.scrape, args=())
    d.daemon = True
    d.start()


def scrape():
    import time
    time.sleep(5)
    # The above part of code takes some time to scrape a webpage, applying
    # some logic, which takes some time to execute, hence I've added a time
    # sleep of 5 secs. But when run with daemon = True, the file is not
    # created. Else it works fine.

    data = [[1, 2, 3, 4], [2224, 34, 34, 34, 34]]
    with open('1.csv', "wb") as f:
        writer = csv.writer(f)
        writer.writerows(data)

3
你为什么要使用守护进程? - Reut Sharabani
2个回答

25
根据多进程守护进程文档,当你的脚本结束工作时,通过设置d.daemon=True,会杀死所有子进程。这发生在它们开始写入之前,因此不会产生任何输出。

7

d.daemon = True 表示子进程会在父进程结束后自动终止,以防止孤儿进程的出现。通过在 d.start() 后添加 d.join(),可以帮助父进程等待子进程结束,而不是在子进程结束前就结束了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接