【问题标题】:How do i make big string with batch code to execute in python?如何使用批处理代码制作大字符串以在 python 中执行?
【发布时间】: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


【解决方案1】:

子进程模块不执行脚本,而只执行单个命令。将您的脚本放在一个单独的文件中(无论如何,它会更容易维护)并使用像cmd.exe externalscript.bat这样的命令行来执行

需要明确的是,这是cmd.exe 限制,因此它仅适用于 Windows。 UNIX/Linux shell 可以通过这种方式执行整个脚本。事实上,如果你在 Windows 上安装了bash(例如通过 WSL 或 Git),它在 Windows 上也可以正常工作,尽管你需要直接调用 shell 而不是使用shell=True。我认为 PowerShell 也可以工作,虽然我还没有尝试过。

(就我个人而言,我很想用 Python 重写批处理脚本...)

【讨论】:

  • 答案应该很明确,这是仅限 Windows 的限制。在shell=True['sh', '-c'] 附加到参数列表的平台上,可以在被解释的代码中传递多个命令。
  • 是的,我觉得我有点迷失了,我深入研究的每个论坛都声称您可以通过这种方式执行多个命令,没有人真正指定它不适用于 w
  • 是的,没错,这是cmd.exe 的限制。
  • 顺便说一句:您可以使用子进程模块运行脚本,例如a = subprocess.Popen("myscript.bat", stdout=subprocess.PIPE, shell=True)
猜你喜欢
  • 2012-07-26
  • 1970-01-01
  • 2021-10-17
  • 2010-10-16
  • 2011-06-15
  • 1970-01-01
相关资源
最近更新 更多