python 使用线程池执行器动态执行

python dynamic execution with threadpoolexecutor

我正在动态加载模块并尝试执行 class 它们包含:

class Test(Services):
    def __init__(self):
        Services.__init__(self)

    def start(self):
        print('start')


services_path = 'services'
s = 'test'
instance = getattr(importlib.import_module(services_path + '.' + s), s.title())

with ThreadPoolExecutor(max_workers=2) as executor:
    tmp = executor.submit(instance.start)
    print(tmp.result())

但是在执行时我收到错误:

TypeError: start() missing 1 required positional argument: 'self'

我会看一下 instance 对象,我认为它可能只是一个 type/class 对象而不是 Test 对象......您正在尝试在未实例化对象的情况下调用该方法

所以你应该实例化 "instance"

instance = getattr(importlib.import_module(services_path + '.' + s), s.title())()

或尝试

# keep "instance" as is
instance = getattr(importlib.import_module(services_path + '.' + s), s.title())
# and
def _instance_start(instance_class):
    return instance_class().start
executor.submit(_instance_start(instance))