为什么在Python的线程处理中出现TypeError [英] Why do I get TypeError in Threading in Python

查看:122
本文介绍了为什么在Python的线程处理中出现TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,这些代码基于我在SO上找到的示例,但是当我运行它时出现错误.请帮忙,我确定它非常简单:

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()

我得到的错误是:

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

推荐答案

错误来自以下行:

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

args参数必须是一个序列,我想您的意图是使用元组,但是将单个值包装在括号中并不能实现这一点.这是您需要将其更改为:

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

这篇关于为什么在Python的线程处理中出现TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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