fi中行的python多进程映射

2024-05-15 18:06:15 发布

您现在位置:Python中文网/ 问答频道 /正文

有谁能告诉我为什么下面的内容没有产生任何输出?在

python mycode.py< file.txt

在霉菌素.py是

^{pr2}$

这只是一个测试程序。在现实生活中,“工作”将被一个计算密集的耗时过程所取代。由于行的顺序并不重要,所以我尝试使用imap_unordered。在


Tags: pytxt内容顺序过程测试程序fileimap
1条回答
网友
1楼 · 发布于 2024-05-15 18:06:15

p.imap_unordered()是迭代器。要推进它,你需要消耗它:

#!/usr/bin/env python
import multiprocessing
import sys
import time

def work(line):
    time.sleep(len(line))
    return line

if __name__ == '__main__':
    pool = multiprocessing.Pool(2)
    for result in pool.imap_unordered(work, sys.stdin):
        sys.stdout.write(result)

如果file.txt包含:

^{pr2}$

则输出为:

bb
ccc
a

如果将最大工人数从2增加到3,则输出为:

a
bb
ccc

要运行它,请在stdin上传递输入:

$ python mycode.py <file.txt

要将输出重定向到另一个文件:

$ python mycode.py <file.txt >output.txt

相关问题 更多 >