Disk Defrag and Disk Clean up using Python Script

时间:2016-11-12 06:03:04

标签: python import python-import popen defragmentation

Can you help me on how to make this script work.

For Defrag

import os;
defragmentation=os.popen('defrag.exe /C').read()
print(defragmentation);

For Disk Clean up

import os;
clean=os.popen('cleanmgr.exe /sagerun:1').read()
print(clean);

Upon trying this scripts, it didnt do anything and no error message prompt. Thank you.

3 个答案:

答案 0 :(得分:1)

  • 如果您的defrag.execleanmgr.exe不在您的path中,则他们将无法执行,并且您不会收到错误消息
  • 您需要以管理员身份运行脚本才能使其正常运行。
  • 您不需要在Python中使用分号终止行

如果要查找可执行文件的正确完整路径,可以使用以下脚本:

paths = os.getenv('path').split(';')
path_defrag = ''

for p in paths:
    if os.access(os.path.join(p, 'defrag.exe'), os.X_OK):
        path_defrag = os.path.join(p, 'defrag.exe')
        break
if not path_defrag:
    print('defrag.exe is not in your path or cannot be executed')
  • 我建议Spectras'想法并在它出现时读取输出而不是一切都完成
  • 此外,我认为Python在这里是一种过度杀伤,一个简单的批处理文件可以完成这项工作

答案 1 :(得分:0)

根据我的评论:我在这里的赌注是脚本完美无缺,但您希望立即看到输出,并且看不到任何内容,就会中止该程序。

但是,read()将停止脚本,直到命令完成。只有这样,pringint才会发生。因此,在命令完成之前,不会显示任何输出。

我会改变它:

with os.popen('cleanmgr.exe /sagerun:1') as fd:
    chunks = iter(lambda: fd.read(1), '')
    for chunk in chunks:
        sys.stdout.write(chunk)

这个想法是按原样进行打印:当指定大小时,read在描述符关闭之前不会循环,只要它读取内容就会返回。

这里效率不高,因为它会逐个读取字符。对于你正在运行的程序来说,它应该没那么重要,而且在不引入python缓冲延迟的情况下阅读更多内容非常复杂。

如果你没有在你的程序中使用输出而只是希望它能够通过,那么你可能最好只是打电话:

import subprocess
subprocess.check_call(['cleanmgr.exe', '/sagerun:1'])

没有其他参数,输出只会转到脚本的输出。该函数在返回之前一直等到命令完成。

答案 2 :(得分:0)

您遇到的问题是因为您尝试从32位进程中启动64位可执行文件。 当您启动脚本的python或cmd提示符为32位时,如果您只指定defrag.exe而没有完整路径,它将以32位模式启动defrag.exe。

并且cleanmgr不会返回任何内容,您应该只返回一个空字符串。 尝试下面的代码,它应该适用于python 32位或64位目标64位操作系统

import os
print('running disk defragmentation, this might take some time ...')
# you might wanna try out with %systemroot%\sysnative\defrag.exe /A first,
# Else, it might really take some time for defragmentation
if sys.maxsize > 2**32:
    defragmentation=os.popen('defrag.exe /C').read() # run from 64-bit        
else:
    defragmentation=os.popen(r'%systemroot%\sysnative\defrag.exe /C').read() # run from 32-bit

print(defragmentation)


print('running disk cleanup, this might take some time ...')
clean=os.popen('cleanmgr.exe /sagerun:1').read() # should works in both 32-bit and 64-bit
print(clean) # cleanmgr run from gui and don't return anything, this should be empty

建议使用子流程,不推荐使用os.popen

import sys
import subprocess

if sys.maxsize > 2**32:
    run_cmd = 'defrag /C' # 64-bit python/cmd
else:
    run_cmd = r'%systemroot%\sysnative\defrag /C' # 32-bit python/cmd

output, err = subprocess.Popen(run_cmd, stdout=subprocess.PIPE, shell=True).communicate()
print(output)
if err:
    print('process fail, error {}'.format(err))
else:
    print('process sucess')

# repeat with run_cmd = 'cleanmgr /sagerun:1'