You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将Batch代码存为长字符串并完整执行?

问题原因

  • 首先你编写的Batch脚本存在语法错误:第一行color b之后的第二行直接写/s /f /q c:\windows\temp\*.*,缺失了命令前缀del,cmd运行到该无意义行时直接报错终止,所以只有第一行命令生效。
  • 其次shlex.split不适合拆分多命令的Batch脚本:shlex是为POSIX风格的单条命令参数拆分设计的,拆分后的列表包含大量不完整的命令片段,shell=True模式下cmd无法正常解析该列表内容。
  • 最后直接传递整段Batch字符串给subprocess默认不会被cmd识别为完整脚本,需要指定cmd的运行参数或者生成临时bat文件运行。

修复方案

方案1:生成临时bat文件运行(最稳定,无转义问题)

先修正Batch脚本的语法错误,替换新版Windows已经弃用的deltree命令,再通过临时文件运行:

import subprocess
import tempfile
import os

# 修正后的完整Batch脚本
commands = """
@echo off
color b  

del /s /f /q c:\windows\temp\*.* 
rd /s /q c:\windows\temp
md c:\windows\temp
del /s /f /q C:\WINDOWS\Prefetch
del /s /f /q %temp%\*.* 
rd /s /q %temp%
md %temp%

:: 替换已弃用的deltree命令
rd /s /q c:\windows\tempor~1 2>nul
rd /s /q c:\windows\temp 2>nul
rd /s /q c:\windows\tmp 2>nul
del /s /f /q c:\windows\ff*.tmp 2>nul
rd /s /q c:\windows\history 2>nul
rd /s /q c:\windows\cookies 2>nul
rd /s /q c:\windows\recent 2>nul
del /s /f /q c:\windows\spool\printers\*.* 2>nul
del c:\WIN386.SWP 2>nul
cls 

FOR /F "tokens=1,2*" %%V IN ('bcdedit 2^>^&1') DO SET adminTest=%%V
IF "%adminTest%"=="Access" goto noAdmin
for /F "tokens=*" %%G IN ('wevtutil.exe el') DO (call :do_clear "%%G")
echo.
echo Quick dett ^<press any key^>
pause >nul
exit

:do_clear
echo clearing %1
wevtutil.exe cl %~1
goto :eof

:noAdmin
echo bot !
echo ^<press any key^>
pause >nul
cls
"""

# 生成临时bat文件
with tempfile.NamedTemporaryFile(mode='w', suffix='.bat', delete=False, encoding='gbk') as f:
    f.write(commands)
bat_path = f.name

# 运行脚本并打印输出
proc = subprocess.Popen(
    bat_path,
    shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    text=True,
    encoding='gbk'
)
for line in proc.stdout:
    print(line.strip())
proc.wait()

# 清理临时文件
os.unlink(bat_path)

方案2:直接传递给cmd运行(无需生成文件)

如果不想生成临时文件,直接把整段脚本用cmd /c包裹运行即可,不需要shlex拆分:

import subprocess

proc = subprocess.Popen(
    f'cmd /c "{commands}"',
    shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    text=True,
    encoding='gbk'
)
for line in proc.stdout:
    print(line.strip())
proc.wait()

注意事项

  • 清理系统目录需要管理员权限,运行Python脚本时请右键选择「以管理员身份运行」,否则大部分删除操作会被拒绝。
  • 脚本中添加2>nul是为了忽略文件不存在、无权限的报错,避免脚本中途异常终止。
  • Windows cmd默认编码为GBK,读写脚本和读取输出时指定encoding='gbk'可避免乱码。

内容的提问来源于stack exchange,提问作者999sha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 12:24:03