树莓派4下Python2.7读取未终止shell进程输出查找指定字符串方案咨询
实现方案
基于Python 2.7 树莓派Linux环境编写,以下代码可同时满足你提出的所有需求。
完整可运行代码
import subprocess import sys import time import fcntl import os # 替换为实际的hex文件路径 hexfileName = "your_firmware.hex" cmd = "./prebuilt/bin/bbb_cc13xx-sbl /dev/ttyACM0 {} cc13x2 -e -p -v".format(hexfileName) # 启动烧录子进程 proc = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, # 合并标准错误到标准输出,避免漏捕获内容 bufsize=1 ) # 将输出管道设置为非阻塞模式,避免读取操作卡住 fd = proc.stdout.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # 初始化配置 timeout = 5 # 超时时间,单位为秒,可根据实际情况调整 start_time = time.time() expression_found = False full_output = "" # 循环检测输出 while time.time() - start_time < timeout: try: chunk = proc.stdout.read() if chunk: # 同步打印输出到终端,效果和os.system一致 sys.stdout.write(chunk) sys.stdout.flush() # 累积全量输出用于检测 full_output += chunk if "Connecting" in full_output: expression_found = True break except IOError: # 无可用输出时跳过 pass time.sleep(0.1) # 结果处理 if expression_found: # 检测到关键词后的逻辑 print "\n已检测到Connecting,执行后续操作" else: # 超时逻辑,先杀掉卡住的子进程避免占用资源 proc.terminate() proc.wait() print "\n超时未检测到Connecting,已终止烧录进程"
功能对应说明
- 同步终端输出:读取到子进程输出后立刻写入标准输出并强制刷新,和
os.system()的显示效果完全一致 - 关键词检测:累积保存所有输出内容,实时匹配
Connecting关键词,匹配成功立刻返回结果 - 超时机制:超时后自动终止烧录脚本进程,避免进程无限卡住占用串口资源
- 全量输出获取:所有输出内容保存在
full_output变量中,可直接用于后续日志记录或故障排查
注意事项
- 如需单独捕获错误输出,去掉
stderr=subprocess.STDOUT配置,单独对stderr文件描述符做非阻塞读取即可 - 脚本运行结束后会自动清理未退出的烧录子进程,不会残留后台进程
内容的提问来源于stack exchange,提问作者Slev1n
相关产品推荐
相关产品推荐

