Guest User

file_flood.py

a guest
May 29th, 2024
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.13 KB | Source Code | 0 0
  1. import asyncio
  2. import aiofiles
  3. import os
  4. import json
  5. import time
  6. from pathlib import Path
  7.  
  8. # Константы
  9. main_directory = '/mnt/filesystem_test/subvol-999-disk-0/storage/blobs/pmw6tvzmf2jv6giyybmmvl4o2ahqlaldsaeha4yx74n5aaaaaaaa'
  10. input_file = 'filelist.txt'
  11.  
  12. def move_cursor_up(lines):
  13.     return f"\033[{lines}A"
  14.  
  15. # Создаем директорию, если она не существует
  16. os.makedirs(main_directory, exist_ok=True)
  17.  
  18. async def create_file(folder, filename, filesize):
  19.     # Создаём директорию, если она не существует
  20.     folder_path = Path(main_directory) / folder
  21.     folder_path.mkdir(parents=True, exist_ok=True)
  22.  
  23.     file_path = folder_path / filename
  24.  
  25.     # Записываем файл в асинхронном режиме
  26.     async with aiofiles.open(file_path, 'wb') as f:
  27.         bytes_to_write = filesize
  28.         # Записываем файл блочно (порциями по 1048576 bytes)
  29.         while bytes_to_write > 0:
  30.             block_size = min(1048576, bytes_to_write)
  31.             await f.write(os.urandom(block_size))
  32.             bytes_to_write -= block_size
  33.  
  34. async def process_line(line):
  35.     json_objects = json.loads(line)
  36.     tasks = [
  37.         create_file(obj['folder'], obj['filename'], obj['filesize'])
  38.         for obj in json_objects
  39.     ]
  40.     await asyncio.gather(*tasks)
  41.     return sum(obj['filesize'] for obj in json_objects), len(json_objects)
  42.  
  43. async def process_file():
  44.     total_files = 0
  45.     total_size = 0
  46.     start_time = time.time()
  47.  
  48.     async with aiofiles.open(input_file, 'r', encoding='utf-8') as f:
  49.         lines = await f.readlines()
  50.         for index, line in enumerate(lines, start=1):
  51.             filesize_sum, file_count = await process_line(line.strip())
  52.             total_size += filesize_sum
  53.             total_files += file_count
  54.  
  55.             # Обновляем статистику каждые 50 строк
  56.             if index % 50 == 0:
  57.                 elapsed_time = time.time() - start_time
  58.                 speed = total_size / elapsed_time if elapsed_time > 0 else 0
  59.                 print(f"Статистика после {index} строк:")
  60.                 print(f"Файлов создано: {total_files}")
  61.                 print(f"Объем: {total_size} байт")
  62.                 print(f"Затраченное время: {elapsed_time:.2f} секунд")
  63.                 print(f"Текущая скорость: {speed:.2f} байт/секунд")
  64.                 print(move_cursor_up(5), end='')  # Перемещаем курсор вверх
  65.  
  66.     # Финальная статистика
  67.     elapsed_time = time.time() - start_time
  68.     speed = total_size / elapsed_time if elapsed_time > 0 else 0
  69.     print(f"Итоговая статистика:")
  70.     print(f"Файлов создано: {total_files}")
  71.     print(f"Объем: {total_size} байт")
  72.     print(f"Затраченное время: {elapsed_time:.2f} секунд")
  73.     print(f"Текущая скорость: {speed:.2f} байт/секунд")
  74.  
  75. if __name__ == '__main__':
  76.     asyncio.run(process_file())
Advertisement
Add Comment
Please, Sign In to add comment