Fix Python – Python Threading String Arguments


Asked By – Anonymous

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

def processLine(line) :
    print "hello";


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

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”.

However I get the following error

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

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.

Now we will see solution for issue: Python Threading String Arguments


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 ','

Or use brackets to make a list:

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

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

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.

This question is answered By – Stephen

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0