【问题标题】:Parallel Program in Python produces no outputPython中的并行程序不产生输出
【发布时间】:2019-02-04 03:38:55
【问题描述】:

我有一个简单的任务。需要为大量文件运行特定功能。此任务可以轻松并行化。

这是工作代码:

# filelist is the directory containing two file, a.txt and b.txt.
# a.txt is the first file, b.xt is the second file
# I pass a file that lits the names of the two files to the main program

from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import sys

def translate(filename):
    print(filename)
    f = open(filename, "r")
    g = open(filename + ".x", , "w")
    for line in f:
        g.write(line)

def main(path_to_file_with_list):
    futures = []
    with ProcessPoolExecutor(max_workers=8) as executor:
        for filename in Path(path_to_file_with_list).open():
            executor.submit(translate, "filelist/" + filename)
        for future in as_completed(futures):
            future.result()

if __name__ == "__main__":
     main(sys.argv[1])

但是,不会创建新文件,即该文件夹不包含 a.txt.x 和 b.txt.x 文件。

上面的代码有什么问题,我怎样才能让它工作?

谢谢。

【问题讨论】:

  • 您的程序包含打印语句。你有任何输出吗?
  • 对文件进行迭代会为您提供文件的行,包括行尾 - 因此您尝试打开名称包含换行符的文件,这实际上不太可能存在。
  • 你也没有关闭文件。如果你不关闭“g”,你可能不会得到任何输出。如果您使用“with”语句打开 f 和 g,它们将始终在块的末尾关闭。
  • futuresmain 的第二个循环中仍然是一个空列表
  • @PaulCornelius 是的,打印语句工作正常

标签: python python-3.x python-2.7 multiprocessing python-multiprocessing


【解决方案1】:

这应该让您走上正确的道路。如果它不起作用并且不是一个明显的错误,那么我怀疑您可能没有正确的所有文件路径......我应该指出,编写文件将受益于线程而不是减少开销的进程。文件 I/O 应该释放 GIL,因此您将从加速中受益(如果您一次复制多行,则会显着增加。)也就是说,如果您只是复制文件,您应该只使用 shutil.copyshutil.copy2

from concurrent.futures import ProcessPoolExecutor, wait
from pathlib import Path
import sys

def translate(filename):
    print(filename)
    with open(filename, "r") as f, open(filename + ".x", , "w") as g:
        for line in f:
            g.write(line)

def main(path_to_file_with_list):
    futures = []
    with ProcessPoolExecutor(max_workers=8) as executor:
        for filename in Path(path_to_file_with_list).open():
            futures.append(executor.submit(translate, "filelist/" + filename))
        wait(futures) #simplify waiting on processes if you don't need the result.
        for future in futures:
            if future.excpetion() is not None:
                raise future.exception() #ProcessPoolEcecutors swallow exceptions without telling you...
        print("done")

if __name__ == "__main__":
     main(sys.argv[1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多