我需要设置一些测试条件来模拟填满的磁盘。我创建了以下内容来简单地将垃圾写入磁盘:
#!/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()
据我所知,通过查看freespace的返回值,write方法不会将文件写入,直到它被关闭,从而使while条件无效。
有没有办法可以直接将数据写入文件?或许是另一种解决方案?
答案 0 :(得分:3)
这是未经测试的,但我想这些内容将是最容易填充磁盘的方法
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
答案 1 :(得分:0)
您可以在写入时尝试/捕获磁盘完全异常。