首页 文章

正确实现Python多处理

提问于
浏览
4

我在这里经历了多处理教程:http://pymotw.com/2/multiprocessing/basics.html

我在下面写了一个脚本作为练习 . 该脚本似乎正在工作,我确实看到在taskmgr中运行了5个新的python进程 . 但是,我的print语句输出多次搜索的同一文件夹 .

我怀疑不是在不同进程之间拆分工作,而是让每个进程都承担整个工作负载 . 我很确定我做错了什么,效率低下 . 有人可以指出我的错误吗?

到目前为止我所拥有的:

def email_finder(msg_id):
    for folder in os.listdir(sample_path):
        print "Searching through folder: ", folder
        folder_path = sample_path + '\\' + folder
        for file in os.listdir(os.listdir(folder_path)):
            if file.endswith('.eml'):
                file_path = folder_path + '\\' + file
                email_obj = email.message_from_file(open(file_path))
                if msg_id in email_obj.as_string().lower()
                    shutil.copy(file_path, tmp_path + '\\' + file)
                    return 'Found: ', file_path
    else:
        return 'Not Found!'

def worker():
    msg_ids = cur.execute("select msg_id from my_table").fetchall()
    for i in msg_ids:
        msg_id = i[0].encode('ascii')
        if msg_id != '':
            email_finder(msg_id)
    return

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()

1 回答

  • 5

    每个子进程都有自己的游标,因此迭代整个ID .

    您需要从数据库中读取 msg_ids 一次,然后将其生成到子进程,而不是让每个子进程自行查询 .

相关问题