小编典典

Python:线程类型错误。函数接受x位置参数,但给定y

python

我目前正在使用Python。我有一个启动功能,可以从消息中获取字符串。我想为每个消息启动线程。

此刻的线程应该只打印出我的消息,如下所示:

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,不明白为什么。异常消息是此消息:

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 =我字符串的长度

我究竟做错了什么?


阅读 135

收藏
2021-01-16

共1个答案

小编典典

所述args的kwargthreading.Thread预计可迭代,并且在迭代被传递到所述目标函数的每个元素。

由于您要提供以下字符串args
t = threading.Thread(target=startSuggestworker, args=(start_keyword))

每个字符都作为单独的参数传递给startSuggestworker

相反,您应该提供args一个元组:

t = threading.Thread(target=startSuggestworker, args=(start_keyword,))
#                                                                  ^ note the comma
2021-01-16