在Python中并行化代码

时间:2016-10-21 01:08:12

标签: python abaqus

我正在使用名为Abaqus的商业分析软件,该软件具有Python接口以读取输出值。

我刚才给出了一个示例代码(不运行):

myOdb包含我从中提取数据的所有信息。需要注意的是,我无法使用2个独立的程序打开文件。

下面显示的代码1和代码2彼此独立工作,他们只需要myOdb。

有没有办法在读取odb后并行化代码1和2?

# Open the odb file 
myOdb = session.openOdb(name=odbPath)

# Code 1
for i in range(1, NoofSteps+1):
    frames = myOdb.steps[stepName].frames 
    lastframe=frames[-1]   
    RFD = lastframe.fieldOutputs['RF'] 

    sum1=0

    for value in RFD.values:
        sum1=sum1+value.data[1]   

# Code 2
for i in range(1, NoofSteps+1):
    frames = myOdb.steps[stepName].frames 
    lastframe=frames[-1]   

    for j in range(4,13):
        file2=open('Fp'+str(j)+stepName,'w')
        b=lastframe.fieldOutputs[var+str(j)]
        fieldValues=b.values
        for v in fieldValues:
            file2.write('%d %6.15f\n' % (v.elementLabel, v.data))

1 个答案:

答案 0 :(得分:2)

如果您尝试做的只是达到基本级别的多处理,那么这就是您所需要的:

import multiprocessing

#Push the logic of code 1 and code 2 into 2 functions. Pass whatever you need
#these functions to access as arguments.

def code_1(odb_object, NoofSteps):
   for i in range(1, NoofSteps+1):
    frames = odb_object.steps[stepName].frames 
    #stepName? Where did this variable come from? Is it "i"?
    lastframe=frames[-1]   
    RFD = lastframe.fieldOutputs['RF'] 

    sum1=0

    for value in RFD.values:
        sum1=sum1+value.data[1]

def code_2(odb_object, NoofSteps):
    for i in range(1, NoofSteps+1):
        frames = odb_object.steps[stepName].frames 
        #stepName? Where did this variable come from? Is it "i"?
        lastframe=frames[-1]   

        for j in range(4,13):
            file2=open('Fp'+str(j)+stepName,'w')
            b=lastframe.fieldOutputs[var+str(j)]
            fieldValues=b.values
            for v in fieldValues:
                file2.write('%d %6.15f\n' % (v.elementLabel, v.data))

if __name__ == "__main__":
    # Open the odb file 
    myOdb = session.openOdb(name=odbPath)
    #Create process objects that lead to those functions and pass the
    #object as an argument.
    p1 = multiprocessing.Process(target=code_1, args=(myOdb,NoofSteps, )) 
    p2 = multiprocessing.Process(target=code_2, args=(myOdb,NoofSteps,)) 
    #start both jobs
    p1.start()
    p2.start()
    #Wait for each to finish.
    p1.join()
    p2.join()
    #Done

隔离" main"你的代码的一部分进入了一个主要的块,就像我上面所示,不是,我的意思是绝对的,不要使用全局变量。确保您使用的所有变量都在每个函数的命名空间中可用。

我建议您更多地了解Python和GIL问题。阅读有关多处理模块here的信息。