Python 脚本不池化

问题描述 投票:0回答:0

首先要注意的是,我对 Python 还是相当陌生,并且做了很多自学工作,所以如果我做了/没有做一些明显或愚蠢的事情,我深表歉意。下面代码中对文件名的引用已被删除,但该位工作正常。我还取消了计算,这样您就可以了解我正在努力实现的目标。

我有一个文本文件,其中包含采用以下形式的数字和字符串字段的行

0,0,0,a,b,c,d
我将其导入数组并附加我在计算过程中使用的其他列。

我需要循环遍历此数组中的每一行,并针对从计算和内存角度来看很昂贵的所有其他行对其进行评估。一旦对每一行进行评估,我就需要为这两条线覆盖数组中的数据。

我的计划是使用多处理池和数组来尽快循环数据,同时每个进程都在数组的同一个副本上工作。这意味着有时多个进程可能会尝试写入同一行。

我已经创建了下面的代码,但我的问题是代码运行,没有通过任何错误消息,但没有“跳转”到 ComputeResult 函数,因为它没有打印“Computing result for... " 当我在该函数中放置一个断点时,行或停止。为什么会这样?任何帮助将不胜感激。

import numpy as np
import multiprocessing as mp

def AnalysisSettingsFunction(FileNumber):

    FilesList = []
    FilesList.append(r"\\...File to import.txt")

    if FileNumber != -1 :
        ImportFile = (FilesList[FileNumber])
    else:
        ImportFile = len(FilesList)

    OtherVariable = 21
    
    return ImportFile, OtherVariable

def ComputeResult(Args):

    ProcessLock, FileNumber, DataSet, RowNumber, LineCount = Args
    
    print(f"Computing result for {RowNumber}", flush=True)

    for C in range(RowNumber+1, LineCount):
        
        RowData = DataSet[RowNumber]
        OtherRow = DataSet[C]

        Value1 = RowData[0]
        Value2 = RowData[1]
        Value3 = OtherRow[0]
        Value4 = OtherRow[1]

        with ProcessLock:
            
            if Value1 > Value3:
                RowData[12] = Value1 * Value2
                OtherRow[12] = Value1 * Value2
            else:
                RowData[12] = Value3 * Value4
                OtherRow[12] = Value3 * Value4

def main(FileNumber):
    
    AnalysisSettings = AnalysisSettingsFunction(FileNumber)
    FileToImport = AnalysisSettings[0]

    #Importing data into array
    RawDataSet = []
    with open(FileToImport) as f:
        for line in f:
            StrippedLine = line.rstrip() + ",0,0,0,0,0,0,0,0,0,0,0,0,1000000,0,1000000,0,100,-100,0,100,-100,0,0,0,0,0"    
            RawDataSet.append(StrippedLine.split(",",))

    LineCount = len(RawDataSet)

    ProcessLock = mp.Lock()
    DataSet = mp.Array(c_wchar_p, np.array(RawDataSet, dtype=str).flatten(), lock=ProcessLock)
    del RawDataSet

    with mp.Pool() as Pool:
        Args = [(ProcessLock, FileNumber, DataSet, i, LineCount) for i in range(LineCount)]
        Pool.starmap_async(ComputeResult, Args)

if __name__ == "__main__":

    print("Script Started")
    AnalysisSettings = AnalysisSettingsFunction(-1)
    NumberofFiles = AnalysisSettings[0]

    for FileNumber in range(NumberofFiles):
        AnalysisSettings = AnalysisSettingsFunction(FileNumber)
        main(FileNumber)
    
    print("Script Finished")
python arrays python-multiprocessing pool
© www.soinside.com 2019 - 2024. All rights reserved.