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
相关产品推荐
相关产品推荐

