无法让多处理功能与我的Python类实例一起使用

问题描述 投票:-1回答:1

基本上,我想为同一对象创建几个实例,并同时分别执行它们。示例代码:

if __name__ == '__main__':
            load_dotenv()

            query = "SELECT username, password FROM students"
            cursor.execute(query)
            records = cursor.fetchall()

            print("Total number of accounts botting up ", cursor.rowcount)

            object_list = list()
            for username, password in records:
                obj = Student(username, password)
                object_list.append(obj)

            instance_list = list()
            for x in object_list:
                p = multiprocessing.Process(target=x.login)
                p.start()
                instace_list.append(p)

            for x in instance_list:
                x.join()

ps:login()是类内部的方法。

到目前为止,我已经让他们全部创建了该类的实例,但是还无法为每个实例执行login方法。

我在终端中收到此错误:

 (student-bot) C:\python\student-bot>Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:\users\alberto\appdata\local\programs\python\python37\lib\multiprocessing\spawn.py", line 99, in spawn_main
    new_handle = reduction.steal_handle(parent_pid, pipe_handle)
  File "c:\users\alberto\appdata\local\programs\python\python37\lib\multiprocessing\reduction.py", line 87, in steal_handle
    _winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE)
PermissionError: [WinError 5] Acceso denegado
[13852:1860:0427/193022.541:ERROR:device_event_log_impl.cc(162)] [19:30:22.541] Bluetooth: bluetooth_adapter_winrt.cc:1055 Getting Default Adapter failed.

python python-3.x multithreading multiprocessing
1个回答
0
投票

您可能想要target=x.login,而不是x.login()。否则,您将调用target.login()返回的任何内容,甚至可能无法调用。一个“正在执行”的过程实际上可能只是主线程,并且是您已经编码x.login()的结果,但实际上所有子过程都没有工作。显示错误消息会很有帮助。还要确保上面的代码在以下列开头的块内:

if __name__ == '__main__':

例如:

import multiprocessing

class Foo:
    def bar(self, i):
        print(i, flush=True)

f = Foo()

if __name__ == '__main__':
    instace_list = list()
    for i in range(3):
        p = multiprocessing.Process(target=f.bar, args=(i,))
        p.start()
        instace_list.append(p)

    for x in instace_list:
        x.join()

打印:

0
1
2
© www.soinside.com 2019 - 2024. All rights reserved.