Python线程字符串参数

2024-06-23 18:48:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python线程和在参数中发送字符串有问题。

def processLine(line) :
    print "hello";
    return;

是的。

dRecieved = connFile.readline();
processThread = threading.Thread(target=processLine, args=(dRecieved));
processThread.start();

其中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)

232是我要传递的字符串的长度,所以我猜它会把它分解成每个字符,然后像那样传递参数。如果我只是正常地调用该函数,它可以正常工作,但我真的希望将它设置为一个单独的线程。


Tags: 函数字符串selfhellotarget参数lineargs
2条回答

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

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

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

args is the argument tuple for the target invocation. Defaults to ().

其次,Python中关于tuplequirk

Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

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

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

您试图创建一个元组,但您只是将字符串括起来:)

添加额外的',':

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

或使用括号列出:

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

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

*self.__args将字符串转换为字符列表,并将它们传递给processLine 功能。如果传递给它一个单元素列表,它将把该元素作为第一个参数传递,在您的例子中,就是字符串。

相关问题 更多 >

    热门问题