在 raspberry PI 上使用 python 2.7 搜索从未完成的 shell 进程返回的表达式

Searching for an expression returned from a shell process that never finishes using python 2.7 on raspberry PI

我安装了 raspberry pi 4 (RPI) 和 python 2.7。在 python 脚本中,我正在执行一个 shell 脚本,它会闪烁连接到 pi 的 µController (µC)。 shell 脚本打印了一些内容,并在打印“正在连接”后进入空闲状态。请注意,此时脚本尚未完成!

现在我想使用子进程(或任何其他函数)将 shell 脚本中的所有打印件转发给我。然后我想检查是否打印了关键词“Connecting”。此外,如果 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。第一个是空 all/most 的时间。

这是一个解决方案,其中子进程的打印结果实时显示在终端上,并且我能够在 stdout 管道中搜索关键字。我也能够毫无错误地终止子进程。我还可以添加超时以及终止子进程。这些代码还在 raspberry pi 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`

欢迎任何评论。