I am having a raspberry pi 4 (RPI) with python 2.7 installed. Within a python script, I am executing a shell script, which flashes a µController (µC) connected to the pi. The shell script prints some stuff and reaches idle after printing "Connecting". Note that the script does not finish at this point!
Now I want to use subprocess (or any other function) to forward me all the prints from the shell script. I do then want to check if the keyphrase "Connecting" has been printed. Besides, I need a timeout if the shell script gets stuck before printing "Connecting". However, I am quite new to python, thus I dont know how to use the subprocess correctly to be able to retrieve the prints from the shell script and set a timeout for the script as well.
Here is some sort of pseudo code:
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...
Is there an easy way to implement my two needs?
EDIT: Adding the prints to the terminal like os.system() does would be great, too.
Best wishes Slev1n
CodePudding user response:
I actually found a simple solution, the mistake is to pipe stderr instead of stdout. The first one being empty all/most of the time.
Here is a solution where the prints from the child process where displayed on the terminal in real time and where I was able to search for a keyword within the stdout pipe. I was also able to terminate the child process without errors. I could also add a timeout as well for terminating the child process. The codes was also validated on raspberry pi 4B with python 2.7.
Here the main process:
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
And here the child process:
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`
Any comments are welcome.