如何在python中的类对象上使用多进程

Jos*_*osh 5 python multiprocess psse

我对 Python 相当陌生,我的经验是通过 Siemens PSS/e 中提供的 API 在 Powerflow 建模中使用它的。我有一个脚本,我已经使用了好几年了,它在大型数据集上运行一些模拟。

为了快速完成,我通常将输入分成多个部分,然后在 IDLE 中运行脚本的多个实例。我最近为输入添加了一个 GUI,并改进了代码以更加面向对象,创建了一个类,GUI 将输入传递给它,然后像原始脚本一样工作。

我的问题是如何从程序本身内部拆分过程而不是制作多个副本?我已经阅读了一些关于 mutliprocess 模块的内容,但我不确定如何将它应用于我的情况。本质上,我希望能够实例化 N 个相同的对象,每个对象都并行运行。

我现在拥有的类(称为 Bot)传递了一组参数并在它运行时创建一个 csv 输出,直到它完成。我有一个单独的代码块,可以在最后将各个部分组合在一起,但现在我只需要了解在我的 GUI 中点击运行后踢出多个 Bot 对象的最佳方法。GUI 中有输入来指定要使用的 N 段的数量。

如果我的问题相当模糊,我会提前道歉。感谢您提供任何信息,因为我有点卡住了,不知道在哪里寻找更好的答案。

Pet*_*ood 2

创建配置列表:

configurations = [...]
Run Code Online (Sandbox Code Playgroud)

创建一个采用相关配置的函数,并使用您的Bot

def function(configuration):
    bot = Bot(configuration)
    bot.create_csv()
Run Code Online (Sandbox Code Playgroud)

创建一个Pool包含您想要使用的 CPU 数量的工作线程:

from multiprocessing import Pool
pool = Pool(3)
Run Code Online (Sandbox Code Playgroud)

多次调用配置列表中的每个配置的函数。

pool.map(function, configurations)
Run Code Online (Sandbox Code Playgroud)

例如:

from multiprocessing import Pool
import os

class Bot:
    def __init__(self, inputs):
        self.inputs = inputs

    def create_csv(self):
        pid = os.getpid()
        print('TODO: create csv in process {} using {}'
              .format(pid, self.inputs))


def use_bot(inputs):
     bot = Bot(inputs)
     bot.create_csv()


def main():
    configurations = [
        ['input1_1.txt', 'input1_2.txt'],
        ['input2_1.txt', 'input2_2.txt'],
        ['input3_1.txt', 'input3_2.txt']]

    pool = Pool(2)
    pool.map(use_bot, configurations)

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

输出:

TODO: create csv in process 10964 using ['input2_1.txt', 'input2_2.txt']
TODO: create csv in process 8616 using ['input1_1.txt', 'input1_2.txt']
TODO: create csv in process 8616 using ['input3_1.txt', 'input3_2.txt']
Run Code Online (Sandbox Code Playgroud)