python-2.7 - 在树莓派上使用 python 2.7 搜索从永远不会完成的 shell 进程返回的表达式
问题描述
我有一个安装了 python 2.7 的树莓派 4 (RPI)。在 python 脚本中,我正在执行一个 shell 脚本,它会闪烁一个连接到 pi 的 µController (µC)。shell 脚本会打印一些内容,并在打印“正在连接”后达到空闲状态。请注意,此时脚本尚未完成!
现在我想使用 subprocess (或任何其他函数)将所有来自 shell 脚本的打印转发给我。然后我确实想检查是否打印了关键词“正在连接”。此外,如果 shell 脚本在打印“正在连接”之前卡住,我需要超时。但是,我对 python 很陌生,因此我不知道如何正确使用子进程才能从 shell 脚本中检索打印并为脚本设置超时。
这是某种伪代码:
output = subprocess.Popen(["./prebuilt/bin/bbb_cc13xx-sbl /dev/ttyACM0 {hexfileName} cc13x2 -e -p -v"], \
stdout=subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
expression_found = False
for i in range(5)
if(output.stdout.find('Expression') != -1):
expression_found = True
break
time.sleep(1)
if(expression_found):
do that..
else:
do this...
有没有一种简单的方法来实现我的两个需求?
编辑:像 os.system() 那样将打印添加到终端也会很棒。
最好的祝愿 Slev1n
解决方案
我实际上找到了一个简单的解决方案,错误是管道 stderr 而不是 stdout。第一个是空的所有/大部分时间。
这是一个解决方案,其中子进程的打印实时显示在终端上,并且我能够在标准输出管道中搜索关键字。我还能够无错误地终止子进程。我还可以添加一个超时来终止子进程。这些代码还在树莓派 4B 上使用 python 2.7 进行了验证。
这里主要流程:
import subprocess, sys
import time
cmd = "contprint.py"
p = subprocess.Popen( cmd , shell=True,
stdout=subprocess.PIPE,
universal_newlines=True)
startTime = time.time()
maxTime = 8
while True:
currentTime = time.time()
if (currentTime - startTime) > maxTime:
p.terminate()
break
else:
output = p.stdout.readline()
print(output)
keyWord = "EOF"
if keyWord in output:
print("Keyword {} has be found".format(keyWord))
p.terminate()
break
if len(output) == 0:
print("Output is empty")
p.terminate()
break
if p.poll() is not None:
print("p.poll is not none")
p.terminate()
break
这里是子进程:
import time, sys
count = 0
while(1):
count += 1
print(count)
try:
sys.stdout.flush()
except:
print("Escape Error!")
time.sleep(0.5)
if(count == 10):
print("EOF")
if(count == 20):
pass`enter code here`
欢迎任何意见。
推荐阅读
- java - JavaFX setText() NullPointerException 即使我设置了控制器和 fxml 标签
- jquery - 所选页码在 JQuery 数据表的服务器端分页中被重置
- tfs-2015 - SSDT - 跟踪 DACPAC 部署中的数据库更改
- javascript - 如何正确缩放图像以适应 maxdim-by-maxdim 正方形区域?
- php - 通过多个数组数据中的数组值返回数组键
- excel - VBA:如何在用户表单列表中均匀地放置项目?
- vbscript - 拆分后vbScript忽略许多空格
- xamarin - Xamarin 存档工具 - 看似正常的错误,但原因不明
- scalatest - println的scalatest Flatespec测试结果
- matlab - Matlab 快速数据类型转换 4x1byte 到 1x32byte