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 ','
processThread.start()
Or use brackets to make a list:
dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved]) # <- 1 element list
processThread.start()
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.
from threading import Thread
from time import sleep
def run(name):
for x in range(10):
print("helo "+name)
sleep(1)
def run1():
for x in range(10):
print("hi")
sleep(1)
T=Thread(target=run,args=("Ayla",))
T1=Thread(target=run1)
T.start()
sleep(0.2)
T1.start()
T.join()
T1.join()
print("Bye")
I hope to provide more background knowledge here.
First, constructor signature of the of method 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 ().
Second, A quirk in Python about tuple
:
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).
On the other hand, a string is a sequence of characters, like 'abc'[1] == 'b'
. So if send a string to args
, even in parentheses (still a sting), each character will be treated as a single parameter.
However, Python is so integrated and is not like JavaScript where extra arguments can be tolerated. Instead, it throws an TypeError
to complain.