简体   繁体   English

如何在后台线程中使用自变量运行其他类中的方法?

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

I have a class with a certain method. 我有一类用某种方法。 This method calls the method of another class, and it does this via a background thread using the threading library in python. 此方法调用另一个类的方法,并使用python中的线程库通过后台线程执行此操作。 However, I also would like to send this method some arguments. 但是,我也想向该方法发送一些参数。

When I tried doing this in the obvious way as shown below, I get an error indicating that there are not enough arguments, because 'self' is included as one of the parameters for the method. 当我尝试以明显的方式执行此操作(如下所示)时,出现一个错误,指示没有足够的参数,因为将'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    

In other.py 在other.py中

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

Basically, I want B to launch the command via a subprocess in the background thread while the program continues on, but I keep getting the error of not enough arguments. 基本上,我希望B在程序继续运行的同时通过后台线程中的子进程启动命令,但是我一直收到参数不足的错误。

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

You need to pass the function callback to Thread and what arguments should be passed. 您需要将函数回调传递给Thread以及应传递的参数。 In the code you provided you called to function which passed the results of that function call to Thread 在您提供的代码中,您调用了function,该函数将该函数调用的结果传递给了Thread

It should be: 它应该是:

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

NOTE: The args parameter expects a tuple. 注意:args参数需要一个元组。 A common mistake when passing a single argument is to pass args=(args) . 传递单个参数时的常见错误是传递args=(args) However, to create a single-element tuple you need a comma args=(args,) 但是,要创建单元素元组,您需要使用逗号args=(args,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM