0

你能帮助我如何使这个脚本工作。

对于碎片整理

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

用于磁盘清理

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

尝试此脚本后,它没有做任何事情,也没有错误消息提示。谢谢你。

4

3 回答 3

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 在这里有点过头了,一个简单的批处理文件就可以完成这项工作
于 2016-11-12T06:13:08.763 回答
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'
于 2016-11-17T06:27:32.617 回答
0

基于我的评论:我敢打赌,脚本可以完美运行,但您希望立即看到输出,而看不到任何输出,就中止程序。

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

我会这样改变它:

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'])

没有其他参数,输出只会转到脚本的输出。该函数等到命令完成后再返回。

于 2016-11-12T06:25:12.003 回答