TomHere TomHere - 1 year ago 107
Python Question

Python: TypeError in Threading. function takes x positional argument but y were given

I am working with python at the moment. I have a start-function, that gets a string from a message. I want to start threads for every message. the thread at the moment should just print out my message like this:

def startSuggestworker(message):

def start():
while True:
response = queue.receive_messages()
message = response.pop()
start_keyword = message.body
t = threading.Thread(target=startSuggestworker, args = (start_keyword))
except IndexError:
print("Messages empty")


At the moment I get a Type Error and don't understand why. The Exception message is this one:

Exception in thread Thread-1:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/", line 914, in _bootstrap_inner
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/", line 862, in run
self._target(*self._args, **self._kwargs)
TypeError: startSuggestworker() takes 1 positional argument but y were given

*y = length of my String

What am I doing wrong?

Answer Source

The args kwarg of threading.Thread expects an iterable, and each element in that iterable is being passed to the target function.

Since you are providing a string for args:
t = threading.Thread(target=startSuggestworker, args = (start_keyword))

each character is being passed as a separate argument to startSuggestworker.

Instead, you should provide args a tuple:

t = threading.Thread(target=startSuggestworker, args = (start_keyword,))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download