首页 > 解决方案 > 子进程不会捕获 powershell 输出

问题描述

subprocess我有一个非常简单的脚本,它使用 Python 的库打印出 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.

标签: pythonpowershellsubprocessoutput

解决方案


不应该用Get-MpComputerStatus引号括起来。

import subprocess

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

print(out.stdout)

UPD:事实证明,这标志着capture_output并且text没有必要。引号中的 PowerShell 命令是唯一的问题。我也同意@tripleee 的观点shell在这里阅读更多。


推荐阅读