You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用PowerShell管道获取Chrome进程启动时间失败问题

解决Python subprocess执行PowerShell带管道命令输出为空的问题

你的问题根源是命令写法错误:在管道后额外添加了powershell,导致第二个PowerShell进程无法接收前一个进程的输出,最终返回空结果。

正确的做法是将完整的PowerShell命令放在单次powershell调用中,管道是PowerShell内部的操作逻辑,不需要重复启动PowerShell进程。

修正后的基础代码

import subprocess
# 将完整的PowerShell管道命令作为整体传入powershell.exe
call = "powershell get-process chrome | Format-Table ProcessName, StartTime"
process = subprocess.Popen(call, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
outputs, errors = process.communicate()
# 解码Windows默认编码的字节流为可读字符串
print(outputs.decode('gbk'))

进阶优化:结构化输出解析

如果需要更方便的后续数据处理,可以让PowerShell返回JSON格式结果,再用Python解析:

import subprocess
import json

call = "powershell get-process chrome | Select-Object ProcessName, StartTime | ConvertTo-Json"
process = subprocess.Popen(call, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
outputs, errors = process.communicate()
# 解析JSON数据为Python列表
process_info = json.loads(outputs.decode('gbk'))
for item in process_info:
    print(f"进程名:{item['ProcessName']},启动时间:{item['StartTime']}")

内容的提问来源于stack exchange,提问作者Ottpocket

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 07:10:53