如何在后台线程中 运行 来自不同 class 的方法,带参数?

How to run a method from a different class in a background thread, with arguments?

我有一个class有一定的方法。此方法调用另一个 class 的方法,它使用 python 中的线程库通过后台线程执行此操作。但是,我也想向这个方法发送一些参数。

当我尝试以如下所示的明显方式执行此操作时,我收到一条错误消息,指出没有足够的参数,因为 'self' 作为该方法的参数之一包含在内。

from other import B
backend = B()
class A():
    .
    .
    .
    def create(file, path):
        background_thread = Thread(target=backend.launch(file, path))
        background_thread.start() 
        print("Hello")
        return    

在other.py

class B():
    .
    .
    .
    def launch(self, file, path)
        cmd = "myprog run " + file + " " + path
        process = subprocess.Popen(
            [cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

基本上,我希望 B 在程序继续运行时通过后台线程中的子进程启动命令,但我一直收到参数不足的错误。

TypeError: launch() missing 1 required positional argument: 'path'

您需要将函数回调传递给Thread 以及应该传递哪些参数。在您提供的代码中,您调用了函数,该函数将函数调用的结果传递给 Thread

应该是:

background_thread = Thread(target=backend.launch, args=(file, path,))
background_thread.start() 

注意:args 参数需要一个元组。传递单个参数时的一个常见错误是传递 args=(args)。但是,要创建单元素元组,您需要一个逗号 args=(args,)