在Python中使用多重处理时如何解决BrokenPipeError - python

我正在学习多进程,在使用队列时遇到此问题之前没有任何问题。本质上,队列已满,但随后似乎出了点问题,它崩溃了。

我在Windows 10上运行python 3.6.8。当我不使用队列时,多处理似乎可以正常工作(我在下面构建了类似的代码片段,而无需学习队列)。

import glob, multiprocessing, os

def appendFilesThreaded(inputDirectory, outputDirectory, inputFileType=".txt", outputFileName="appended_files.txt"):
    files = glob.glob(inputDirectory+'*'+inputFileType)
    fileQueue = multiprocessing.Queue()
    for file in files:
        fileQueue.put(file)
    threadsToUse = max(1, multiprocessing.cpu_count()-1)
    print("Using " + str(threadsToUse) + " worker threads.")
    processes = []
    for i in range(threadsToUse):
        p = multiprocessing.Process(target=appendFilesWorker, args=(fileQueue,outputDirectory+"temp-" + str(i) + outputFileName))
        processes.append(p)
        p.start()
    for process in processes:
        process.join()
    with open(outputDirectory + outputFileName, 'w') as outputFile:
        for i in range(threadsToUse):
            with open(outputDirectory+"temp-" + str(i) + outputFileName) as fileToAppend:
                outputFile.write(fileToAppend.read())
            os.remove(outputDirectory+"temp-" + str(i) + outputFileName)
    print('Done')
def appendFilesWorker(fileQueue, outputFileNamePath):
    with open(outputFileNamePath, 'w') as outputFile:
        while not fileQueue.empty:
            with open(fileQueue.get()) as fileToAppend:
                outputFile.write(fileToAppend.read())

if __name__ == '__main__':
    appendFilesThreaded(inputDir,outputDir)

我希望它可以成功附加文件,但是会崩溃。结果为BrokenPipeError: [WinError 232] The pipe is being closed

参考方案

发现了问题:调用queue.empty不正确。您需要括号(例如queue.empty()

我会留下我尴尬的错误,以防它对他人有所帮助:)

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…