Python 线程字符串参数

标签 python python-3.x multithreading arguments python-multithreading

我在使用 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/

相关文章:

python - 警告 :0 terminating async callback error in cv2

python - 设置两个不同的日志记录级别

c - thrd_busy 和 mtx_lock()/mtx_timedlock()

python - 在单个 python 进程中混合绿色线程和 native 线程是否安全?

python - 函数参数概念

python - 我们如何获取 IAM 用户、他们的组和策略?

python - 如何在 Python 中将字符串转换为时间元组

java - 使用数据报 UDP 发送和接收确认

java - 内存不足错误: unable to create new native thread while using Executor

python - 在 scipy 最小化期间​​打印当前评估的参数