python - 将字典传递给 Python 中的线程函数

标签 python multithreading dictionary

所以,我有一个带有 1 个参数的函数 explain(item)。此参数旨在成为具有 8-9 个键的字典。当我调用 explain(item) 时一切正常。但是当我调用时(items 是同一个变量)

threads.append(threading.Thread(target = explain, args=(item)))
threads[i].start()
threads[i].join()

我遇到这样的错误:

Exception in thread Thread-72:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: explain() takes exactly 1 argument (10 given)

我做错了什么?

最佳答案

看起来您打算将单项元组作为 args 参数传递给 threading.Thread() 但使用 args=(item) 等同于 args=item。您需要添加一个逗号来创建元组,因此它将是 args=(item,):

threads.append(threading.Thread(target = explain, args=(item,))).

如果没有尾随逗号,括号只是对表达式进行分组的一种方法,例如:

>>> (100)  # this is just the value 100
100
>>> (100,) # this is a one-element tuple that contains 100
(100,)

关于python - 将字典传递给 Python 中的线程函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22542866/

相关文章:

c# - 多定时器 WPF 应用程序,调用线程必须是 STA 错误

java - 基于列表的 if 语句不起作用 - Java

multithreading - 操作系统中的轻量级线程

Pythonic 字符串操作

java - 从 map 中检索对象

c# - 指定的可执行文件不是此操作系统平台的有效应用程序。 Python绘图仪

python - Flask socket-io,有时客户端调用会卡住服务器

python - 使用 for 循环创建一个 DF 时,Pandas concat 无法按预期工作

python - 如何离线安装 Pytorch?

c# new thread from timer handle 问题