【问题标题】:Subprocess won't capture powershell output子进程不会捕获 powershell 输出
【发布时间】:2021-02-24 19:38:25
【问题描述】:

我有一个非常简单的脚本,它使用 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 捕获输出。

【问题讨论】:

  • 您是否将capture_output 标志设置为True?默认为False,与设置stdout不兼容。
  • 我尝试按照您的建议将capture_output 设置为True(由于ValueError 必须删除stdout),但仍然给我bad 输出(b'Get-MpComputerStatus\r\n')。
  • 是的,我说这些标志不兼容。

标签: python powershell subprocess output


【解决方案1】:

Get-MpComputerStatus 不应括在引号中。

import subprocess

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

print(out.stdout)

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

【讨论】:

  • 好的,有了你的回答,我设法确定了问题所在。那是牙套。保留我的标志 (stdout = subprocess.PIPE,) 或使用你的标志都可以。核心问题是牙套。 (将在 5 分钟内标记为已回答)
  • @ProgramerBeginner 很高兴听到,我会相应地编辑我的答案。
  • shell=True 在这里也是错误的。它可能无害,但无用且可能令人困惑。
猜你喜欢
  • 2016-07-21
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-29
  • 2012-05-10
  • 2020-05-23
相关资源
最近更新 更多