1

サーバー上の特定のディレクトリに保存されているものの量を取得するために、毎晩実行するスクリプトがあります。これは私がそのコア部分に使用している関数です:

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            try:
                fp = os.path.join(dirpath, f)
                total_size += os.path.getsize(fp)
                print str(total_size)+" bytes / "+str(size(total_size))+" counted"+" <------------ current position: "+start_path+" : "+f
                for location in locations_dict:
                    if locations_dict[location][1] != "":
                        print str(location)+": "+str(size(locations_dict[location][1]))
            except OSError, e:
                print e
    return total_size

何らかの理由で、手動で実行すると異なる値が得られます

$ du -hc [path to dir]

Python を使用すると、20551043874445 バイトになります (20.5 TB に変換されます)。28 TBを取得します (値をバイト単位で取得するduことなく、現在再実行しています)。-h

明らかに、その Python 関数には何かが欠けていますが、何がどのように欠けているのかわかりません。何か案は?

4

1 に答える 1

8

duサイズを 512 バイト ブロック単位で示します。ファイル サイズが 512 の倍数でない場合は、du切り上げます。Python で同等の値を取得するには、 を使用する代わりに、結果の属性をos.path.getsize()使用os.stat()して使用します。st_blocks

total_size += os.stat(fp).st_blocks * 512;
于 2016-02-11T20:43:44.187 に答える