文件夹/目录删除进度

时间:2013-10-06 10:04:46

标签: python python-2.7 directory progress

我正在使用pyqt编写应用程序。需要删除包含子文件夹和许多文件的文件夹。文件夹的路径位于usb磁盘中。删除正在进行时,我想向用户显示更新的进度条。这是我尝试在删除时计算百分比的示例代码。

#!/usr/bin/python2.7
import subprocess
import os

def progress_uninstall_dir():
    uninstall_path = "path/to/folder"
    usb_mount = "path/to/usb/mount"
    if not os.path.exists(uninstall_path):
        print ("Directory not found.")
    else:
        proc=subprocess.Popen("du -ck " + usb_mount + " | grep total | cut -f 1", shell=True, stdout=subprocess.PIPE, )
        inintial_usb_size = int(proc.communicate()[0])
        proc=subprocess.Popen("du -ck " + uninstall_path + " | grep total | cut -f 1", shell=True, stdout=subprocess.PIPE, )
        folder_size_to_remove = int(proc.communicate()[0])
        delete_process = subprocess.Popen('rm -rf ' + uninstall_path,  shell=True)
        while delete_process.poll() is None:
            proc=subprocess.Popen("du -ck " + usb_mount + " | grep total | cut -f 1", shell=True, stdout=subprocess.PIPE, )
            current_size =   int(proc.communicate()[0])
            diff_size = int(inintial_usb_size - current_size)
            percentage = float(diff_size/folder_size_to_remove)*100
            print (percentage)


progress_uninstall_dir()

但是,上面的代码总是以0为百分比。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的问题可能是由于计算percentage时的整数除法造成的。您现在拥有的代码将一个整数除以另一个整数(可能获得值0),然后将结果转换为浮点数。通过在分割之前将两个整数中的一个转换为浮点数来获得更好的服务:

percentage = float(diff_size)/folder_size_to_remove*100