使用threadpoolexecutor的python动态执行

使用threadpoolexecutor的python动态执行,python,threadpoolexecutor,Python,Threadpoolexecutor,我正在动态加载模块并尝试执行它们包含的类: 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 + '.' +

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

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'

我会看看
实例
对象,我认为它可能只是
类型
/
对象,而不是
测试
对象。。。如果您试图在没有实例化对象的情况下调用该方法

因此,您应该实例化“实例”

或者试试类似的东西

# 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))   

看起来您可能并没有实际创建一个实例,而是得到了一个classattr。。通过使用调试器单步执行并查询with子句之前的
实例
,您就可以知道。顺便说一句,动态加载模块会很快给您带来麻烦。。请记住导入操作的完整结构(缓存等),我并不是说这样做是错误的,因为该功能是在标准库中提供的。我只是说,通常可以重新考虑一点,然后使用更传统的导入,以更简单的结构结束。
# 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))