简体   繁体   中英

Disk Defrag and Disk Clean up using Python Script

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.

  • If your defrag.exe or cleanmgr.exe are not in your path , they won't execute and you won't get an error message
  • You would need to run the scripts as an administrator to make them work.
  • You don't need to terminate your lines with a semi-colon in Python

If you want to find the the correct full path of your executable, you can use the following script:

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')
  • I'd suggest to Spectras' idea and read the output while it comes and not once everything is finished
  • In addition I think Python is an overkill here, a simple batch file will do the job

Building upon my comment: my bet here is the script works perfectly, but you expect to see output right away and, not seeing any, abort the program.

However, read() will stop your script until the command completes. And only then will the pringint happen. Thus, no output will ever be displayed until after the command has completed.

I would change it like this:

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

The idea being to print as it goes: when a size is specified, read does not loop until the descriptor is closed, it returns as soon as it reads something.

It's not the most efficient here as it will read chars one by one. For the programs you're running it should not matter much, and reading more without introducing buffering delays with python is complex.

If you are not using the output in your program and just want it to pass through, maybe you'd be better off just calling :

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

With no additional parameters, output will just go to your script's output. The function waits until the command completes before returning.

the problem you face is because you are trying to launch 64-bit executable out of 32-bit process. When your python or cmd prompt you launch the scripts is 32-bit, it will launch defrag.exe in 32-bit mode if you just specify defrag.exe alone without full path.

And cleanmgr does not return anything, you should just get an empty string back. Try code below, it should works for both python 32-bit or 64-bit targeting 64-bit OS

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

Suggest to use subprocess instead, os.popen is deprecated

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM