あなたが直面している問題は、32 ビット プロセスから 64 ビットの実行可能ファイルを起動しようとしているためです。スクリプトを起動する python または cmd プロンプトが 32 ビットの場合、defrag.exe をフル パスなしで単独で指定すると、defrag.exe が 32 ビット モードで起動します。
また、cleanmgr は何も返しません。空の文字列を返すだけです。以下のコードを試してみてください。64 ビット OS をターゲットとする 32 ビットまたは 64 ビットの Python の両方で動作するはずです。
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
代わりに subprocess を使用することをお勧めします。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'