I have this piece of code in which I try to send an UDP datagram in a new thread
import threading, socket
address = ("localhost", 9999)
def send(sock):
sock.sendto("Message", address)
print "sent"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
threading.Thread(target=send, args=(s)).start()
But when I try to give the socket as an argument to the function, a TypeError exception is thrown:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in
self.__target(*self.__args, **self.__kwargs)
TypeError: send() argument after * must be a sequence, not _socketobject
What that means?
The Python "TypeError: write () argument must be str, not dict" occurs when we pass a dictionary to the write () method. To solve the error, convert the dictionary to a string or access a specific key in the dictionary that has a string value.
How to Avoid TypeError? Python always checks the type of object we are passing for operation and whether a particular object type supports the operation. Python will throw a TypeError. We can avoid this error by adding an extra step or try-catch before such an operation.
So when we execute it, python still generates TypeError, as it says element index 2, i.e. the third element is still an integer. So now we have to make the rest two elements also as integers to work properly. In the above program, you can see inside the join function, we have converted each element of list1 into a string by typecasting.
Python will throw a TypeError. We can avoid this error by adding an extra step or try-catch before such an operation. Suppose we want to join two lists.
You need to add a comma - ,
- after your variable s
. Sending just s to args=() is trying to unpack a number of arguments instead of sending just that single arguement.
So you'd have threading.Thread(target=send, args=(s,)).start()
Also the splat - *
- operator might be useful in this question explaining it's usage and unzipping arguments in general
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With