如何使用多进程或多线程客户端在 python 中获取工作进度条?

Pyt*_*oob 4 multithreading multiprocessing pygobject python-2.7 progress-bar

这就是基本的想法。

在阅读 python 文档中的所有内容时,我无法理解它们。太多了,无法理解。

有人可以解释我如何使用多线程(或多进程)客户端获取工作进度条吗?

或者有没有其他方法可以在不锁定程序 GUI 的情况下“更新”进度条?

此外,当这些类型的客户端尝试同时访问文件时,我确实阅读了有关“I/O”错误的内容,以及当应用程序未正确调用多线程库时的 X 服务器错误。我如何避免他们?

这次我没有写代码,我不想以僵尸进程或类似的东西结束(然后强制关闭PC,我讨厌破坏宝贵的数据......)。我需要先明白我在做什么!

Luk*_*.py 5

像下面这样的东西可能会让你开始?- 我试图尽可能多地注释来解释这个过程。

from Tkinter import *
from Queue import Queue
import ttk, threading
import time

queue = Queue()
root = Tk()

# Function to do 'stuff' and place object in queue for later #
def foo():
    # sleep to demonstrate thread doing work #
    time.sleep(5)
    obj = [x for x in range(0,10)]
    queue.put(obj)

# Create thread object, targeting function to do 'stuff' #
thread1 = threading.Thread(target=foo, args=())

# Function to check state of thread1 and to update progressbar #
def progress(thread, queue):
    # starts thread #
    thread.start()

    # defines indeterminate progress bar (used while thread is alive) #
    pb1 = ttk.Progressbar(root, orient='horizontal', mode='indeterminate')

    # defines determinate progress bar (used when thread is dead) #
    pb2 = ttk.Progressbar(root, orient='horizontal', mode='determinate')
    pb2['value'] = 100

    # places and starts progress bar #
    pb1.pack()
    pb1.start()

    # checks whether thread is alive #
    while thread.is_alive():
        root.update()
        pass

    # once thread is no longer active, remove pb1 and place the '100%' progress bar #
    pb1.destroy()
    pb2.pack()

    # retrieves object from queue #
    work = queue.get()
    return work

work = progress(thread1, queue)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。让我知道你的想法!