Python多线程参数错误

use*_*843 0 python multithreading

我刚刚开始使用多线程,所以我想我会做一个小而简单的例子:

import time
import threading

def count(who):
        count = 1
        while count <= 5:
                print who + " counted to: " + str(count)
                time.sleep(0.1)
                count += 1

thread1 = threading.Thread(target=count, args=('i'))
thread1.start()
Run Code Online (Sandbox Code Playgroud)

哪个效果很好并打印出以下内容:

>>> i counted to: 1
>>> i counted to: 2
>>> i counted to: 3
>>> i counted to: 4
>>> i counted to: 5
Run Code Online (Sandbox Code Playgroud)

然而,奇怪的是,当我想将参数更改为另一个时,例如:"john":

thread1 = threading.Thread(target = count,args =('john'))

希望它会产生:

>>> john counted to: 1
>>> john counted to: 2
>>> john counted to: 3
>>> john counted to: 4
>>> john counted to: 5
Run Code Online (Sandbox Code Playgroud)

但是,它会产生错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: count() takes exactly 1 argument (4 given)
Run Code Online (Sandbox Code Playgroud)

我真的不确定这里发生了什么......有谁知道吗?

Reu*_*ani 5

添加逗号以明确表示您想要一个元组:

thread1 = threading.Thread(target=count, args=('john', ))
Run Code Online (Sandbox Code Playgroud)

目前python认为括号是多余的,因此("john")评估"john"哪四个字符,因此你得到的消息.