Convenient Python Command Runner

Here is a little piece of code which I tend to reuse quite often. It basically runs a command and return True if the command executed successfully or False if it did not. The second item in the return tuple is the stdout output of the command if any or the error if there was an error executing the command.

import subprocess

def runcmd(cmd):
  try:
    f = subprocess.Popen(cmd,shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    stdout = f.stdout.read();
    stderr = f.stderr.read();
   
    if f.stdout.close() == None and  f.stderr.close() == None:
      return True,stdout,stderr
    else:
      return False,stdout,stderr
  except OSError,x:
    return False,x
As usual the source code can be found here.

No comments:

Post a Comment