如何用subprocess.run实现system_profiler结合grep筛选分辨率?
问题解决:subprocess.run中管道命令不生效的处理方法
问题原因
你在subprocess.run的列表参数里传入|时,这个符号会被当作普通参数传递给system_profiler命令,而非被Shell解析为管道操作——只有Shell才会识别并处理|这种管道语法,所以后面的grep Resolution根本没被执行。
两种解决办法
方法1:启用Shell解析(简单直接)
把整个终端命令作为字符串传入subprocess.run,并设置shell=True,让Shell来处理管道逻辑:
import subprocess res = subprocess.run( "system_profiler SPDisplaysDataType | grep Resolution", capture_output=True, shell=True, text=True # 让输出为字符串而非字节流,方便后续处理 ) # 打印结果 print(res.stdout.strip())
注意:这种方式如果命令包含用户输入内容,存在Shell注入风险,需谨慎使用。
方法2:分两次调用subprocess(更安全)
不依赖Shell管道,手动将第一个命令的输出作为第二个命令的输入,避免Shell注入风险:
from subprocess import run, PIPE # 第一步:执行system_profiler并捕获输出 system_profiler_output = run( ["system_profiler", "SPDisplaysDataType"], stdout=PIPE, text=True ).stdout # 第二步:将第一步的输出传给grep处理 res = run( ["grep", "Resolution"], input=system_profiler_output, capture_output=True, text=True ) # 打印结果 print(res.stdout.strip())
内容的提问来源于stack exchange,提问作者kjdfsjdsa kafsjna
相关产品推荐
相关产品推荐

