Python线程字符串参数 [英] Python Threading String Arguments

查看:192
本文介绍了Python线程字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem with Python threading and sending a string in the arguments.

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

.

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

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

Where dRecieved is the string of one line read by a connection. It calls a simple function which as of right now has only one job of printing "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是我要传递的字符串的长度,因此我猜想它会将其分解成每个字符并尝试传递类似的参数.如果我只是正常调用该函数,则效果很好,但我真的想将其设置为单独的线程.

232 is the length of the string that I am trying to pass, so I guess its breaking it up into each character and trying to pass the arguments like that. It works fine if I just call the function normally but I would really like to set it up as a separate thread.

推荐答案

您正在尝试创建一个元组,但是您只是在给一个字符串加上括号:)

You're trying to create a tuple, but you're just parenthesizing a string :)

添加一个额外的',':

Add an extra ',':

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

或使用方括号列出列表:

Or use brackets to make a list:

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


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

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

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

这篇关于Python线程字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆