Python-多处理守护进程

时间:2014-12-15 23:01:55

标签: python multiprocessing

我创建了一个多进程,它创建了一个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.scrap, args=())
    d.daemon = True
    d.start()


def scrap():
    import time
    time.sleep(5)
    # The above part of code takes some time to scrap 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)

2 个答案:

答案 0 :(得分:8)

根据multiprocess daemon documentation,当脚本结束时设置d.daemon=True,其作业将终止所有子进程。这种情况发生在它们开始写入之前,因此不会产生任何输出。

答案 1 :(得分:0)

d.daemon = True 表示子进程在父进程结束后自动终止,防止出现孤儿进程。 join() 是有帮助的,只需在 d.join() 后添加 d.start(),这样父进程就不会在子进程之前结束;相反,父进程会等到子进程结束。