Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import platform
- import sys
- import shutil
- import ctypes
- import tempfile
- SHERB_NOCONFIRMATION = 1
- SHERB_NOPROGRESSUI = 2
- SHERB_NOSOUND = 4
- def EmptyRecycleBin(options=SHERB_NOCONFIRMATION or SHERB_NOPROGRESSUI or SHERB_NOSOUND):
- ctypes.windll.shell32.SHEmptyRecycleBinA(None, None, options)
- def get_free_space(folder):
- free_bytes = ctypes.c_ulonglong(0)
- ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
- return int(round(free_bytes.value/1024))
- def get_win_temp_path():
- p = "WINDIR"
- if p in os.environ:
- return os.path.join(os.environ[p], "temp")
- # for param in os.environ.keys():
- # if (str.upper(param) == "WINDIR"):
- # return os.environ[param] + "\\temp"
- return "Error"
- def clear_folder(folder):
- for the_file in os.listdir(folder):
- file_path = os.path.join(folder, the_file)
- try:
- if os.path.isfile(file_path):
- os.unlink(file_path)
- else:
- shutil.rmtree(file_path)
- print("[Deleted] ", file_path)
- except:
- print(str(sys.exc_info()[1]))
- def clear_IE_cache():
- try:
- os.system("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8")
- print("Выполнено\n")
- except:
- print(str(sys.exc_info()[1]))
- def checkConf():
- print("Проверяем наличие файла конфигурации...")
- chk = os.path.exists('main_clear_temp.cfg')
- if chk == False:
- print("Файл не найден, создаем новый с дефолтными настройками...")
- file = open("main_clear_temp.cfg", "w+")
- file.writelines("10000000")
- file.close()
- print("Файл создан.")
- return " "
- def main():
- if platform.system() == 'Windows':
- print("Читаем конфигурацию...")
- checkConf()
- f = open("main_clear_temp.cfg", "r")
- s = f.readline()
- try:
- my_limit_free_space = int(s)
- except:
- print("Ошибка в файле конфигурации устанавливаем лимит по умолчанию 10 Gb")
- my_limit_free_space = 10000000
- print("Ок")
- f.close()
- my_temp = tempfile.gettempdir()
- my_win_temp = get_win_temp_path()
- my_drive = my_temp[0:2]
- free_space1 = get_free_space(my_drive)
- print("На диске [" + my_drive + "] свободно [" + str(free_space1) + "] Kb лимит [" + str(my_limit_free_space) + "] Kb\n")
- if (free_space1 < my_limit_free_space):
- print("Директория пользовательского TEMP [" + my_temp + "]")
- print("Очистка пользовательского TEMP\n")
- clear_folder(my_temp)
- print("\nВыполнено\n")
- print("Директория системного TEMP [" + my_win_temp + "]")
- print("Очистка системного TEMP\n")
- if (my_win_temp != "Error"):
- clear_folder(my_win_temp)
- print("\nВыполнено\n")
- else:
- print("Невозможно определить путь к системному каталогу TEMP!")
- print("Очистка кэша IE")
- clear_IE_cache()
- print("Очистка корзины")
- EmptyRecycleBin(options=SHERB_NOCONFIRMATION)
- print("Выполнено")
- free_space2 = get_free_space(my_drive)
- print("\nНа диске [" + my_drive + "] свободно [" + str(free_space2) + "] Kb лимит [" + str(my_limit_free_space) + "] Kb")
- print("Освобождено " + str(free_space2 - free_space1) + " Kb\n")
- else:
- print("Лимит не превышен. Очистка не требуется.")
- print("Работа скрипта завершена.")
- else:
- print("Работа скрипта возможна только на платформе Windows.")
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement