为什么要无限调用此函数?

时间:2019-04-09 08:34:27

标签: python recursion sqlite

我正在编写一个代码,该代码应该使用递归函数( scan_folder )获得一些文件名,然后使用第二个函数( update_db )将它们写入sqlite数据库)。

第一个问题是,每当 scan_folder()调用自身时,它便会立即调用 update_db(),尽管不是这样。因此,数据库会更新很多。也许我可以在完成后弹出传递给第二个函数的值,但我想知道为什么会这样。

class Sub:

    def __init__(self, parent, scan_type):
        self.database = ConnectionToDatabase()
        self.database_name = ConnectionToDatabase().database_name()

    def scan_folder(self):
        connection = sqlite3.connect(self.database_name)

        try:
            cursor = connection.cursor()

            for file_name in os.listdir(self.parent):
                if file_name.endswith('.srt'):
                    if self.scan_type is True:
                        cursor.execute('SELECT count(*) FROM subs WHERE name = ?', (file_name,))

                else:
                    current_path = "".join((self.parent, "/", file_name))
                    if os.path.isdir(current_path):
                        dot = Sub(current_path, self.scan_type)

                        # I THINK HERE IS THE ERROR, ACCORDING TO PYCHARM DEBUGGER
                        # HERE THE update_db() IS CALLED AND ONLY AFTER IT FINISHES, dot.scan_folder() BEGINS
                        dot.scan_folder()

            connection.close()  # Closes connection that adds subtitle names into the database

        finally:
            self.database.update_database(dirty_files_amount)

这里开始第二个功能:

class ConnectionToDatabase:
    def __init__(self):
        self.database = './sub_master.db'

    def update_database(self, dirty_files_amount):
        connection_update = sqlite3.connect(self.database)
        cursor = connection_update.cursor()

            for sub_name in to_update:
                cursor.execute('UPDATE subs SET ad_found = 1 WHERE name = ?', (sub_name,))
                connection_update.commit()

        connection_update.close()

2 个答案:

答案 0 :(得分:0)

这只是预感,但是就在这里:

dot = Sub(current_path, self.scan_type)

您将其设置为等于子方法,并且在该方法中您具有:

 self.database = ConnectionToDatabase()
 self.database_name = ConnectionToDatabase().database_name()

这通过update_db所在的ConnectionToDatabase类进行调用

答案 1 :(得分:0)

当我调用scan_folder时,它进入并且if / else语句获取当前目录中的每个文件和文件夹。当它在那里找不到其他任何内容时,它不会跳回到上一个目录,而是会先调用update_db。

最好的办法是重新编写整个内容,如前所述,这些函数正在做很多事情。

相关问题