【发布时间】:2021-11-21 14:11:27
【问题描述】:
花了好几个小时试图解决这个问题。我试图在 python 中使用我的批处理代码作为长字符串 (""") 创建一个变量,例如:
commands = """color b
/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 /y c:\windows\tempor~1
deltree /y c:\windows\temp
deltree /y c:\windows\tmp
deltree /y c:\windows\ff*.tmp
deltree /y c:\windows\history
deltree /y c:\windows\cookies
deltree /y c:\windows\recent
deltree /y c:\windows\spool\printers
del c:\WIN386.SWP
cls
FOR /F "tokens=1, 2 * " %%V IN ('bcdedit') 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^>
:do_clear
echo clearing %1
wevtutil.exe cl %1
goto :eof
:noAdmin
echo bot !
echo ^<press any key^>
cls
pause"""
它是一个简单的缓存清理器,我的主要目标是执行整个代码块,我只是将关于颜色 b 的输出输出到 python 终端,其他命令甚至不执行。
然后我“排序”命令,以便我可以使用subprocess.Popen 执行它们
commandlist = shlex.split(commands)
但是当我尝试 subprocess.Popen(commandlist, stdout=subprocess.PIPE, shell=True) 时,只是 colorb 得到输出
【问题讨论】:
-
顺便说一句,很抱歉缩进很糟糕
-
您需要将其写入文件并执行,或者将其作为单行命令写入,您可以将其传递给 cmd.exe /C ...
-
如前所述,Popen 并非旨在执行脚本。尝试将该字符串拆分为子字符串列表,然后尝试使用 for 循环
-
@cards,它只在不能处理脚本的 Windows 上——这不是 Popen 限制,而是 cmd.exe 限制。
-
@Charles Duffy 很高兴知道,谢谢!
标签: python string shell cmd subprocess