子进程不会捕获 powershell 输出

Subprocess won't capture powershell output

我有一个非常简单的脚本,它使用 Python 的 subprocess 库打印出 powershell 输出:

import subprocess

out = subprocess.run(
    ['powershell', '-command', '"Get-MpComputerStatus"'],
    stdout = subprocess.PIPE,
    shell = True
    )

print(out.stdout)

我打印出来的输出是 b'Get-MpComputerStatus\r\n',这是错误的。

预期输出是各种计算机统计信息的列表(请自行查看 运行 powershell -command "Get-MpComputerStatus")。

我也试过 os.system('powershell -command "Get-MpComputerStatus"') 有效,但我无法使用 os.system.

捕获输出

Get-MpComputerStatus 不应包含在引号中。

import subprocess

out = subprocess.run(
    ['powershell', '-command', 'Get-MpComputerStatus'],
    stdout = subprocess.PIPE
    )

print(out.stdout)

UPD: 事实证明,标志 capture_outputtext 不是必需的。引号中的 PowerShell 命令是唯一的问题。我也同意@tripleee 关于 shell 的观点。阅读更多 here.