Skip to content Skip to sidebar Skip to footer

Check Output Of A Python Command

I have a python script which tries to run an external command and look for result of the command. And it needs to use the value 'count=' from the output of the external command COU

Solution 1:

p = subprocess.Popen(['python','blah.py'],stdout=subprocess.PIPE)
whileTrue:
  line = proc.stdout.readline()
  iflen(line) != 0:
    print"success"#if this code works, expanding to your regex should also work

Solution 2:

I wrote the following C program:

#include"stdio.h"intmain(){
    printf ("count=199");
    return0;
}

... which I called countOutput.c and the following Python script, modified from yours:

import subprocess, re

COUNT_EXP = re.compile("count=(.*)")
cmd = "./countOutput" # external command
p = subprocess.Popen(cmd,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b''):
    result = COUNT_EXP.match(line)
    if result:
        print"count is equal to " + result.group(1)

... which I called countTest.py, and then ran:

$ python countTest.py
count is equal to 199

... which all works as expected. I'd therefore tend to agree with @kichik in thinking that the external command that you're using may be writing to stderr rather than stdout.

Solution 3:

It might be printing that to stderr. Try redirecting that one to PIPE as well and read data from there. You can also append 2>&1 to the end of the command to get stderr redirected to stdout by the shell. You might have to add shell=True for that.

Post a Comment for "Check Output Of A Python Command"