我需要设置一些测试条件来模拟已满的磁盘。我创建了以下内容来简单地将垃圾写入磁盘:
#!/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()
Run Code Online (Sandbox Code Playgroud)
据我所知,通过查看空闲空间的返回值,write 方法在文件关闭之前不会写入文件,从而使 while 条件无效。
有没有办法可以直接将数据写入文件?或者也许还有其他解决方案?
这是未经测试的,但我想沿着这些思路的东西将是轻松填充磁盘的最快方法
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
Run Code Online (Sandbox Code Playgroud)