Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Thread()中参数的2位参数不起作用_Python_Python 2.7_Python Multithreading - Fatal编程技术网

Python Thread()中参数的2位参数不起作用

Python Thread()中参数的2位参数不起作用,python,python-2.7,python-multithreading,Python,Python 2.7,Python Multithreading,下面是我的问题的相关代码片段: from threading import Thread . . . def do_post(thread_no): print "Starting thread no: " + thread_no + "\n" . . . for i in range(0,MAX_THREADS): try: t=Thread(target=do_post, args=('%d'%i)) t.st

下面是我的问题的相关代码片段:

from threading import Thread
.
.
.
def do_post(thread_no):
       print "Starting thread no: " + thread_no + "\n"

.
.
.

for i in range(0,MAX_THREADS):
        try:
            t=Thread(target=do_post, args=('%d'%i))
            t.start()

.
.
当MAX_THREADS>10时,我会收到错误消息:
TypeError:do_post()正好接受1个参数(给定2个)


如何使其接受2位数字?

您可能希望将
元组传递给
args

args=('%d'%i,)
正如您所拥有的,您只需传递一个字符串,该字符串被解压成比它应该的更多的参数

考虑:

def printstuff(*args):
    print args,len(args)

printstuff(*("1"))   #('1',) 1
printstuff(*("10"))  #('1', '0') 2
printstuff(*("10",)) #('10',) 1

您可能希望将
元组
传递给
args

args=('%d'%i,)
正如您所拥有的,您只需传递一个字符串,该字符串被解压成比它应该的更多的参数

考虑:

def printstuff(*args):
    print args,len(args)

printstuff(*("1"))   #('1',) 1
printstuff(*("10"))  #('1', '0') 2
printstuff(*("10",)) #('10',) 1
args=(…,)
需要传递一个序列,而不是一个标量值,所以在
('%d'%i)
后面加一个逗号:

('%d'%i)
与字符串
'%d'%i
相同

(“%d”%i,)
是元组,其第一个元素为
“%d”%i


不过,顺便说一下,您不必传递线程编号

您可以使用:

 name = threading.current_thread().name
相反



如果希望更改线程的名称,可以通过
name
参数传递任何字符串。比如说,

t = threading.Thread(target=worker, name=str(i))
导致

I am: 0
I am: 1
I am: 2
I am: 3
args=(…,)
需要传递一个序列,而不是一个标量值,所以在
('%d'%i)
后面加一个逗号:

('%d'%i)
与字符串
'%d'%i
相同

(“%d”%i,)
是元组,其第一个元素为
“%d”%i


不过,顺便说一下,您不必传递线程编号

您可以使用:

 name = threading.current_thread().name
相反



如果希望更改线程的名称,可以通过
name
参数传递任何字符串。比如说,

t = threading.Thread(target=worker, name=str(i))
导致

I am: 0
I am: 1
I am: 2
I am: 3

谢谢我不知道。名字的存在。使代码更整洁。谢谢。我不知道。名字的存在。使代码更整洁。