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
相关产品推荐
相关产品推荐

