简体   繁体   English

Python 线程和 PySimpleGUI

[英]Python threading and PySimpleGUI

--REVISED WITH SOLUTION FROM MikeyB-- --根据 MikeyB 的解决方案修订--

Thanks to Mikey for pointing out a simple solution.感谢 Mikey 指出了一个简单的解决方案。 I feel sometimes too much thought is put into a solution, and its a simple overhead solution that resolves the issue.我觉得有时会在解决方案中考虑太多,而这是解决问题的简单开销解决方案。

I have added in a small function that loops through my directories that I want monitored, and sets a variable to True or False.我添加了一个小函数,它循环遍历我想要监视的目录,并将变量设置为 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

This is then called in the PySimpleGUI event loop然后在 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()

--Original Post-- ——原帖——

I have a program that looks in directories defined through a function, and if there are files, it parses these files, and then it moves the data to a database.我有一个程序在通过函数定义的目录中查找,如果有文件,它会解析这些文件,然后将数据移动到数据库中。 If there are files in the directories when the program starts it runs as intended, but when a new file is added the function does not execute.如果程序启动时目录中有文件,它会按预期运行,但是当添加新文件时,该功能不会执行。 It seems that the infinite loop is not executing through directory.似乎无限循环不是通过目录执行的。

I have a UI through PySimpleGUI that is using a "while True:" loop, so I have to spin off the function through a thread.我通过 PySimpleGUI 有一个使用“while True:”循环的 UI,所以我必须通过一个线程来分离该函数。 I am using a queue, and I am trying to identify where I need a "while True:" loop to continuously look in the folder for new files.我正在使用一个队列,我试图确定我需要“while True:”循环的位置,以不断在文件夹中查找新文件。

Below is a portion of the code(indentations below are not proper):下面是代码的一部分(下面的缩进不正确):

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

You can look for new things, poll hardware, do any king of "checking" that doesn't take a long time in the PySimpleGUI event loop in your code.您可以在代码中的 PySimpleGUI 事件循环中寻找新事物、轮询硬件、进行任何不需要很长时间的“检查”。

By adding a timeout to your read call your event loop will run periodically.通过向 read 调用添加超时,您的事件循环将定期运行。 Use this to periodically check for your new files.使用它来定期检查您的新文件。 This is also the same technique that can be used to check for incoming messages from threads using a Queue.这也是可用于使用队列检查来自线程的传入消息的相同技术。

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

You're running yours every second.你每一秒都在运行你的。 This should be fine for polling for new files.这对于轮询新文件应该没问题。 Add your while loop into your event loop.将您的 while 循环添加到您的事件循环中。 If it's too long, spin out as a thread as you said and replace the check_for_changes with check_for_message_from_threads.如果它太长,就像你说的那样作为一个线程旋转,并用 check_for_message_from_threads 替换 check_for_changes。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM