You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python线程传参TypeError:函数需1参数却传入字符串长度个参数的问题

线程调用函数触发TypeError:参数数量不匹配

报错信息

TypeError: go_to_main_coords() takes 1 positional argument but 13 were given

原正常运行代码

def go_to_main_coords(device, main_coords):
    click(device, (9, 908))
    click(device, (9, 908))
    go_to_coords(device, main_coords)


main_thread = threading.Thread(target=go_to_coords, args=(main_device, support_coords))
support_thread = threading.Thread(target=go_to_main_coords, args=(support_device, main_coords))
#Start threads
main_thread.start()
support_thread.start()

#going to coords
main_thread.join()

修改后报错的代码

def go_to_main_coords(device):
    click(device, (9, 908))
    click(device, (9, 908))
    click(device, (40, 820))
    click(device, (260, 800))
    click(device, (270, 400))

main_thread = threading.Thread(target=go_to_coords, args=(main_device, support_coords))
support_thread = threading.Thread(target=go_to_main_coords, args=(support_device))
# Start threads
main_thread.start()
support_thread.start()

# going to coords
main_thread.join()

问题原因

核心问题出在threading.Thread的args参数使用错误:

  • args要求传入元组类型的参数集合,用来给target函数传递参数
  • 你写的args=(support_device)并不是元组,只是给变量套了括号,Python会把字符串support_device当作可迭代对象,自动拆分成单个字符作为独立参数传递给go_to_main_coords
  • 字符串"emulator-5564"刚好有13个字符,所以函数收到13个参数,但它只定义了1个参数,因此触发TypeError

你之前保留第二个参数时能运行,是因为拆分出来的13个字符中,第一个被device接收,剩下的12个被第二个参数“承接”了,属于巧合,不是正确的解决方式。

解决方法

给args的单元素加上逗号,让它成为合法的元组:

support_thread = threading.Thread(target=go_to_main_coords, args=(support_device,))

内容的提问来源于stack exchange,提问作者Westec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:17:07