0

I am trying to get status of postfix in my centos machine. There is a simple command called "postfix status" which returns status of postfix whether its on or off.

This it the minimal python code I came up with after going through previous answers. I've gone through this link : stack overflow link

import subprocess
op = subprocess.run(['postfix', 'status'], stdout=subprocess.PIPE)
print("output is :",op)

The output I am getting is somewhat different than expected

postfix/postfix-script: the Postfix mail system is not running
output is : CompletedProcess(args=['postfix status'], returncode=1, stdout=b'')

It seems like my python script isn't capturing the output. And output gets printed on terminal instead of being fed in to my script. What am I doing wrong? Extra Info: I tried replacing "postfix","status" with "ls","-l" in my script, and it seems to work fine, is there issue with how the command postfix status works?

tripleee
  • 175,061
  • 34
  • 275
  • 318
manjy
  • 109
  • 1
  • 2
  • 12
  • 1
    It looks like an error, so maybe you also need to capture `stderr`. – Gino Mempin Jan 30 '21 at 06:57
  • I don't know why this question is marked duplicate, when it clearly wasn't. Not sure what the community is doing, anyway, after lots of debugging, I found out that nothing was wrong with the code, this is happening because of how the linux command "postfix" is designed. So there's no fix for this. Other commands will give desired behavior but "postfix" doesn't. – manjy Oct 23 '21 at 10:51

1 Answers1

0

As you can read in the subprocess docs, subprocess.run returns a CompletedProcess instance. You are printing the string representation of that object, instead of the actual output of your command, which is saved in the stdout and stderr properties of that object. Additionally, postfix prints its output directly to the console, because you are only capturing the standard output (stdout), but errors are printed to the standard error stream (stderr). A working version of your code would be like this :

import subprocess
op = subprocess.run(['postfix', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("output is : ", op.stdout)
print("errors are : ", op.stderr)

Or, you can have both information and errors in the stdout by changing stderr=subprocess.PIPE to stderr=subprocess.STDOUT

TheEagle
  • 5,808
  • 3
  • 11
  • 39