2

I have a c executable which gets data from a iot hardware and print information on console using printf. I want to run this executable from python which I am able to do so using subprocess.call in following way

subprocess.call(["demoProgram", "poll"])

and print the output to console. But I need to capture this output(printf) using my python code to process information further in real time. How can I capture this output using subprocess in real time?

prattom
  • 1,625
  • 11
  • 42
  • 67
  • If one of the suggested answers solved your problem, please accept it. If you solved this problem on your own, it would be helpful if you could provide your answer and mark it as the accepted solution. Or if you are still having issues, please update your question with more details. – Jonathan Ellington Mar 24 '17 at 16:57

2 Answers2

1

The following opens a subprocess and creates an iterator from the output.

import subprocess
import sys

proc = subprocess.Popen(['ping','google.com'], stdout=subprocess.PIPE)

for line in iter(proc.stdout.readline, ''):
    print(line)  # process line-by-line

This solution was modified from the answer to a similar question.

Community
  • 1
  • 1
-1

if you're using python 2x

have a look at the commands module

import commands

output=commands.getoutput("gcc demoProgram.c") #command to be executed
print output

for python3x

use the subprocess module

import subprocess

output=subprocess.getoutput("gcc demoProgram.c") #command to be executed
print output
Akshay Apte
  • 1,539
  • 9
  • 24
  • I don't think it will work with real time output. Since mine c program is always running and printing on console. – prattom Mar 24 '17 at 06:54