4

我需要设置一些测试条件来模拟已填满的磁盘。我创建了以下内容来简单地将垃圾写入磁盘:

#!/usr/bin/python

import os
import sys
import mmap

def freespace(p):
    """
    Returns the number of free bytes on the drive that ``p`` is on
    """
    s = os.statvfs(p)
    return s.f_bsize * s.f_bavail 

if __name__ == '__main__':

    drive_path = sys.argv[1]
    output_path = sys.argv[2]

    output_file = open(output_path, 'w')

    while freespace(drive_path) > 0:
        output_file.write("!")
        print freespace(drive_path)
        output_file.flush()

    output_file.close()

据我所知,通过查看来自空闲空间的返回值,write 方法在文件关闭之前不会将文件写入,从而使 while 条件无效。

有没有办法可以将数据直接写入文件?或者另一种解决方案?

4

2 回答 2

4

这是未经测试的,但我想这些方面的东西将是轻松填充磁盘的最快方法

import sys
import errno

write_str = "!"*1024*1024*5  # 5MB

output_path = sys.argv[1]

with open(output_path, "w") as f:
    while True:
        try:
            f.write(write_str)
            f.flush()
        except IOError as err:
            if err.errno == errno.ENOSPC:
                write_str_len = len(write_str)
                if write_str_len > 1:
                    write_str = write_str[:write_str_len/2]
                else:
                    break
            else:
                raise
于 2012-12-10T11:47:17.420 回答
0

您可以在写入时尝试/捕获磁盘已满异常。

于 2012-12-10T11:28:43.763 回答