1

我正在使用 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以百分比形式给出。任何帮助,将不胜感激。

4

1 回答 1

0

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

percentage = float(diff_size)/folder_size_to_remove*100
于 2013-10-06T10:16:16.147 回答