Python 线程和 PySimpleGUI

2023-12-03

--根据 MikeyB 的解决方案进行了修改--

感谢 Mikey 指出了一个简单的解决方案。我觉得有时候解决方案需要考虑太多,而一个简单的开销解决方案就可以解决问题。

我添加了一个小函数,该函数循环遍历我想要监视的目录,并将变量设置为 True 或 False。

def file_check(working_pdf):
    if len(gb1(working_pdf, '*.pdf')) == 0:
        pdf_available = False

    if len(gb1(working_pdf, '*.pdf')) > 0:
        pdf_available = True

    return pdf_available

然后在 PySimpleGUI 事件循环中调用

    if files_available is True:
        for client in client_running_list:
            working_pdf, ext = folder_Func(client)
            pdf_available = file_check(working_pdf)
            if pdf_available is True:
                analyzer_queue.put(client)
                for x in range(10):
                    t = Thread(target=analyzer)
                    t.daemon = True
                    t.start()

--原帖--

我有一个程序,它会查找通过函数定义的目录,如果有文件,它会解析这些文件,然后将数据移动到数据库。如果程序启动时目录中有文件,它将按预期运行,但是当添加新文件时,该函数不会执行。看来无限循环不是通过目录执行的。

我通过 PySimpleGUI 有一个 UI,它使用“while True:”循环,因此我必须通过线程分离该函数。我正在使用队列,并且试图确定在哪里需要“while True:”循环来连续在文件夹中查找新文件。

下面是部分代码(下面的缩进不正确):

def analyzer():
while True:
    client = analyzer_queue.get()
    working_pdf, archive_path_datetime = folder_Func(client)
    while True:
        if len(gb1(working_pdf, '*.pdf')) == 0:
            break
        else:
            print(f'Found files in ', client, ' folder. Starting Parse.')
            ##########################################################
            # Start Parse of PDF's
            # Calls pdf parse function.
            # Arguments are Client Number, and PDF to parse.
            # Returns DF of items to insert into SQL Database
            ##########################################################
            ch(working_pdf)
            for pdf in gb1(working_pdf, "*.pdf"):
                items_found_df = pdf_parse(client, pdf)


            ##########################################################
            # Connect to SQL Server and insert items
            # Calls database connection function.
            ##########################################################
                azureDBengine = sqlalchemyConn()
                items_found_df.to_sql("MainData_Capture",azureDBengine,if_exists='append',method='multi',index=False)


            ##########################################################
            # Move file to Archive
            ##########################################################
                if not ospath.exists(archive_path_datetime):
                    osmakedirs(archive_path_datetime)
                    print("Created Archive Folder.")
                file_move(working_pdf, archive_path_datetime, pdf)
            print('All Files Processed.')
            analyzer_queue.task_done()
while True:
    event_dashboard, values_dashboard = dashboard_form.Read(timeout=1000)
    if dashboard_form is None or event_dashboard == 'Exit':
        dashboard_form.Close()
        break

    for client in active_client_list:
        client_start_button_action(client, event_dashboard, dashboard_form)
        client_stop_button_action(client, event_dashboard, dashboard_form)

    if event_dashboard == 'Start Analyze':
        dashboard_form.FindElement(f'Start Analyze').Update(disabled=True)
        dashboard_form.FindElement(f'Stop Analyze').Update(disabled=False)
        print('Analyzer Started')

        for client in client_running_list:
            analyzer_queue.put(client)
        for x in range(10):
            t = Thread(target=analyzer)
            t.daemon = True
            t.start()

    if event_dashboard == 'Stop Analyze':
        dashboard_form.FindElement(f'Stop Analyze').Update(disabled=True)
        dashboard_form.FindElement(f'Start Analyze').Update(disabled=False)
        print('Analyzer Stopped')
        analyzer_queue.empty()

您可以在代码中的 PySimpleGUI 事件循环中寻找新事物、轮询硬件、执行任何不需要花费很长时间的“检查”。

通过向读取调用添加超时,您的事件循环将定期运行。使用它定期检查您的新文件。这也是可用于使用队列检查来自线程的传入消息的相同技术。

while True:             # Event Loop
    event, values = window.read(timeout=500)        # returns every 500 ms
    if event in (None, 'Exit'):
        break
    if check_for_changes():
        do_something()       

你每一秒都在运行你的。这对于轮询新文件应该没问题。将 while 循环添加到事件循环中。如果太长,请按照您所说的方式旋转为线程,并将 check_for_changes 替换为 check_for_message_from_threads。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 线程和 PySimpleGUI 的相关文章

随机推荐