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. 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.
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
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.
TypeError: launch() missing 1 required positional argument: 'path'
You need to pass the function callback to Thread and what arguments should be passed. In the code you provided you called to function which passed the results of that function call to Thread
It should be:
background_thread = Thread(target=backend.launch, args=(file, path,))
background_thread.start()
NOTE: The args parameter expects a tuple. A common mistake when passing a single argument is to pass args=(args)
. However, to create a single-element tuple you need a comma args=(args,)