Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

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):
    print(message)

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

start()

At the moment I get a TypeError 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/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/threading.py", 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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,))
#                                                                  ^ note the comma

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...