我刚刚开始使用多线程,所以我想让自己成为一个小而简单的示例:
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()
效果很好,并打印出以下内容:
>>> i counted to: 1
>>> i counted to: 2
>>> i counted to: 3
>>> i counted to: 4
>>> i counted to: 5
但是,奇怪的是,当我想将参数更改为另一个变量时:“ john”:
线程1 = 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
但是,它会引发错误:
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)
我真的不确定这里发生了什么...有人知道吗?
添加一个逗号以明确表明您想要一个元组:
thread1 = threading.Thread(target=count, args=('john', ))
目前python认为括号是多余的,因此("john")
求出"john"
哪个是四个字符,因此得到的消息是。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句