你能帮助我如何使这个脚本工作。
用于碎片整理
import os;
defragmentation=os.popen('defrag.exe /C').read()
print(defragmentation);用于磁盘清理
import os;
clean=os.popen('cleanmgr.exe /sagerun:1').read()
print(clean);在尝试此脚本时,它没有执行任何操作,也没有错误消息提示。谢谢。
发布于 2016-11-12 14:13:09
defrag.exe或cleanmgr.exe不在您的path中,它们将不会执行,您也不会收到错误消息中以分号结束行
如果要查找可执行文件的正确完整路径,可以使用以下脚本:
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')的工作
发布于 2016-11-12 14:25:12
基于我的评论:我打赌脚本可以完美地工作,但您希望立即看到输出,而没有看到任何输出,然后中止程序。
但是,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-17 14:27:33
您面临的问题是因为您试图从32位进程中启动64位可执行文件。当您的python或cmd提示您启动脚本是32位时,如果您只指定defrag.exe而不指定完整路径,它将在32位模式下启动defrag.exe。
并且cleanmgr不返回任何内容,您应该只返回一个空字符串。尝试下面的代码,它应该适用于针对64位操作系统的python 32位或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'https://stackoverflow.com/questions/40560050
复制相似问题