3

所以我有一个小应用程序可以搜索我电脑上的所有 xml 文件,将文件名为 44 位的文件复制到“输出”文件夹。

问题是最终用户需要指示任务的进度和剩余时间。

这是复制文件的模块:

xml_search.py

import os
import re
from threading import Thread
from datetime import datetime
import time
import shutil
import winsound

os.system('cls')

def get_drives():
    response = os.popen("wmic logicaldisk get caption")
    list1 = []
    t1 = datetime.now()
    for line in response.readlines():
        line = line.strip("\n")
        line = line.strip("\r")
        line = line.strip(" ")
        if (line == "Caption" or line == ""):
            continue
        list1.append(line + '\\')
    return list1


def search1(drive):
    for root, dir, files in os.walk(drive):
        for file in files:
            if re.match("\d{44}.xml", file):
                filename = os.path.join(root, file)
                try:
                    shutil.copy(filename, os.path.join('output', file))
                except Exception as e:
                    pass

def exec_(callback):
    t1 = datetime.now()
    list2 = []   # empty list is created
    list1 = get_drives()
    for each in list1:
        process1 = Thread(target=search1, args=(each,))
        process1.start()
        list2.append(process1)

    for t in list2:
        t.join()  # Terminate the threads

    t2 = datetime.now()
    total = str(t2-t1)
    print(total, file=open('times.txt', 'a'), end="\n")
    for x in range(3):
        winsound.Beep(2000,100)
        time.sleep(.1)
    callback()


if __name__ == "__main__":
    exec_()
4

2 回答 2

2

下面的代码使用进度条库,它显示

指示任务的进度和剩余时间

import progressbar
from time import sleep

bar = progressbar.ProgressBar(maxval=1120, \
    widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.ETA()])
bar.start()
for i in range(1120):
    bar.update(i+1)
    sleep(0.1)
bar.finish()

您需要将上述修改后的代码添加到您的代码中。因此,在您的情况下,您需要计算文件的数量并将其作为输入提供给ProgressBar构造函数的maxval参数并删除sleep调用。

建议的带有进度条的解决方案应该适用于一个线程。如果您坚持使用多个线程,您将需要弄清楚如何启动进度条以及将更新放在哪里。

于 2019-10-20T10:47:40.380 回答
0

尝试实现一个定时器装饰器,如下所示:

import time


def mytimer(func):
    def wrapper():
        t1 = time.time()
        result = func()
        t2 = time.time()
        print(f"The function {func.__name__} was run {t2 - t1} seconds")
        return result

    return wrapper

@mytimer
def TimeConsumingFunction():
    time.sleep(3)
    print("Hello timers")

TimeConsumingFunction()

输出:

/usr/bin/python3.7 /home/user/Documents/python-workspace/timers/example.py
Hello timers
The function TimeConsumingFunction was run 3.002610206604004 seconds

Process finished with exit code 0
于 2019-10-20T20:21:50.617 回答