我在使用 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 是我试图传递的字符串的长度,所以我猜它会将它分解为每个字符并尝试传递这样的参数。如果我只是正常调用该函数,它工作正常,但我真的很想将它设置为一个单独的线程。
最佳答案
你正在尝试创建一个元组,但你只是给一个字符串加上括号:)
添加一个额外的',':
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
功能。如果您将一个元素列表传递给它,它将将该元素作为第一个参数传递 - 在您的情况下是字符串。
关于Python 线程字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3221655/