线程函数无法回想自己(python 2.7)

时间:2018-02-07 16:03:45

标签: python multithreading

在我的kivy应用程序中,我有一个不断检查名称(客户端)列表更新的线程函数,该列表存储当前连接的客户端的名称(来自程序的插槽部分),当函数结束时我让它自己重复检查过程。但它不会起作用:

def check_names(self):
    for name in names:
        if name not in self.namelist.adapter.data:
            self.namelist.adapter.data.extend([name])
    print "checked names"
    time.sleep(2)
    self.check_names()

print "\nstarting name-checking process"
check_names_thread = threading.Thread(target=check_names)
check_names_thread.start()

我收到此错误:

   File "C:\Python27\lib\threading.py", line 754, in run
     self.__target(*self.__args, **self.__kwargs)
 TypeError: check_names() takes exactly 1 argument (0 given)

当我添加一个参数时,像这样:

check_names_thread = threading.Thread(target=check_names, args=" ")

我收到此错误:

Exception in thread Thread-4:
 Traceback (most recent call last):
   File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
     self.run()
   File "C:\Python27\lib\threading.py", line 754, in run
     self.__target(*self.__args, **self.__kwargs)
   File "D:/04 - Media/Python Projects/4 - Networking/Send_Variable_Test/Server.py", line 136, in check_names
     self.check_names()
 AttributeError: 'str' object has no attribute 'check_names'

我该如何解决这个问题?

编辑: 这是完整的图片:

class MainScreen(Screen):

    def check_names(self):
        for name in names:
            if name not in self.namelist.adapter.data:
                self.namelist.adapter.data.extend([name])
        print "checked names"
        time.sleep(2)
        self.check_names()

    print "\nstarting name-checking process"
    check_names_thread = threading.Thread(target=check_names, args=" ")
    check_names_thread.start()

2 个答案:

答案 0 :(得分:0)

为什么self作为函数的参数?这是针对类实例的方法,这不是一种方法。删除该参数,只需使用check_names()来调用它。

答案 1 :(得分:0)

如果你想要一个普通函数,那么你的循环不应该涉及递归:

def check_names():
    while True:
        for name in names:
            if name not in self.namelist.adapter.data:
                self.namelist.adapter.data.extend([name])
        print "checked names"
        time.sleep(2)

但现在你遇到了如何退出这个功能的问题; - )