根据隐式呼叫via 101的方法,Your own helpful answer是解决问题的最快方法,这是由于shell=True
(^
-转义|
可以保护它免受预先解释by 101的影响)
正如链接的答案所暗示的,不要使用powershell
twice:将作为PowerShell管道的single command传递给对powershell.exe
的单个调用,这意味着使用-Command
(-c
)参数.[1]
而在语法方面是100 is convenient(将整个命令行作为single string提供),它isn't necessary和causes overhead是因为必须创建额外的cmd.exe
进程-更不用说need for careful escaping了,以防止cmd.exe
对命令行的部分进行不必要的预先解释,就像手头的情况一样.
因此,consider calling 100 directly,在这种情况下,需要|
的no转义,但最好是pass the command as an array,其第一个元素是目标executable,其后续元素是单独指定的参数:
# ...
# Construct the PowerShell CLI call as an *array*:
# The target executable, followed by the arguments to pass to it.
call = "powershell.exe", "-c", "Get-Process chrome | Format-Table ProcessName, StartTime"
# Make the call, but do NOT use `shell=True`
process = subprocess.Popen(call, stdout=subprocess.PIPE, stderr=None)
# ...
顺便说一句:
[1]请注意,相比之下,PowerShell(Core)CLI为pwsh
,现在为requires,使用-Command
/-c
.
[2]在Windows上,may仍然传递作为整个命令行的单个字符串(仅使用"..."
引号),但在类似Unix的平台上,必须使用数组才能传递参数.(然而,在argument-less调用中,可执行文件的名称或路径在两个平台上都可以作为字符串而不是单元素数组传递.此外,with 101传递单个字符串(即使带有嵌入的参数)在两个平台上都有效,因为该字符串成为传递给shell 可执行文件的单个参数.)