Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

multithreading - Why do I get TypeError in Threading in Python

I've got the following code which is based off an example i found here on SO, but when i run it i get an error. Please help, i'm sure its very simple:

def listener(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('',port))
    sock.settimeout(1) # n second(s) timeout
    try:
        while True:
            data, addr = sock.recvfrom(1024)
            print data
    except socket.timeout:
        print 'Finished'

def startListenerThread(port):
    threading.Thread(target=listener, args=(port)).start()

The error i get is:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
    self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 477, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: listener() argument after * must be a sequence, not int
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error is coming from the following line:

threading.Thread(target=listener, args=(port)).start()

The args parameter needs to be a sequence, I think your intention is to use a tuple, but wrapping a single value in parentheses does not accomplish this. Here is what you need to change it to:

threading.Thread(target=listener, args=(port,)).start()

Here is a simple example showing the difference:

>>> (100)  # this is just value 100
100
>>> (100,) # this is a tuple containing the value 100
(100,)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...