Python:线程处理中的TypeError.函数接受x位置参数,但给定y [英] Python: TypeError in Threading. function takes x positional argument but y were given
问题描述
目前,我正在使用Python.我有一个启动功能,可以从消息中获取字符串.我想为每条消息启动线程.
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()
此刻我得到一个TypeError
,却不明白为什么.异常消息是这样的:
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 =我的字符串的长度
*y = length of my String
我在做什么错了?
推荐答案
threading.Thread
的args
kwarg需要一个可迭代的对象,并且该可迭代对象中的每个元素都将传递给目标函数.
The args
kwarg of threading.Thread
expects an iterable, and each element in that iterable is being passed to the target function.
由于您要提供args
的字符串:
t = threading.Thread(target=startSuggestworker, args=(start_keyword))
Since you are providing a string for args
:
t = threading.Thread(target=startSuggestworker, args=(start_keyword))
每个字符都作为单独的参数传递给startSuggestworker
.
each character is being passed as a separate argument to startSuggestworker
.
相反,您应该为args
提供一个元组:
Instead, you should provide args
a tuple:
t = threading.Thread(target=startSuggestworker, args=(start_keyword,))
# ^ note the comma
这篇关于Python:线程处理中的TypeError.函数接受x位置参数,但给定y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!