Python线程字符串参数

Ano*_*ous 131 python multithreading

我遇到Python线程问题并在参数中发送字符串.

def processLine(line) :
    print "hello";
    return;
Run Code Online (Sandbox Code Playgroud)

.

dRecieved = connFile.readline();
processThread = threading.Thread(target=processLine, args=(dRecieved));
processThread.start();
Run Code Online (Sandbox Code Playgroud)

其中dRecieved是连接读取的一行字符串.它调用一个简单的函数,到目前为止只有一个打印"hello"的工作.

但是我收到以下错误

Traceback (most recent call last):
File "C:\Python25\lib\threading.py", line 486, in __bootstrap_inner
self.run()
File "C:\Python25\lib\threading.py", line 446, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: processLine() takes exactly 1 arguments (232 given)
Run Code Online (Sandbox Code Playgroud)

232是我试图传递的字符串的长度,所以我猜它会将其分解为每个字符并尝试传递这样的参数.如果我只是正常调用函数,它工作正常,但我真的想将它设置为一个单独的线程.

Ste*_*hen 261

你正在尝试创建一个元组,但你只是用字符串括起来:)

添加额外的',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()
Run Code Online (Sandbox Code Playgroud)

或使用括号制作列表:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()
Run Code Online (Sandbox Code Playgroud)

如果你注意到,从堆栈跟踪: self.__target(*self.__args, **self.__kwargs)

*self.__args将您的字符串转换成字符的列表,将它们传递给processLine 函数.如果您传递一个元素列表,它将传递该元素作为第一个参数 - 在您的情况下,字符串.

  • 如果您的 arg2 具有默认值,请执行此操作。`threading.Thread(target=thread_function, args=(arg1,),kwargs={'arg2': arg2})` (4认同)

the*_*eld 12

我希望在这里提供更多的背景知识。

首先,方法threading::Thread 的构造函数签名:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
Run Code Online (Sandbox Code Playgroud)

args是目标调用的参数元组。默认为 ()。

其次,Python 中的一个怪癖tuple

空元组由一对空括号构成;包含一项的元组是通过在值后面加上逗号来构造的(将单个值括在括号中是不够的)。

另一方面,字符串是一个字符序列,例如'abc'[1] == 'b'. 因此,如果将字符串发送到args,即使在括号中(仍然是刺痛),每个字符都将被视为单个参数。

然而,Python 是如此集成,不像 JavaScript 那样可以容忍额外的参数。相反,它会抛出一个TypeError抱怨。