Advertisement
Guest User

Untitled

a guest
Jun 25th, 2012
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. import subprocess
  2. import shlex
  3.  
  4. def run_command(command, expected_retcodes = 0, stdin = None):
  5.     """run a command and raise an exception if retcode not in expected_retcode"""
  6.  
  7.     # we want expected_retcode to be a tuple but will manage integers
  8.     if type(expected_retcodes) == type(0):
  9.         expected_retcodes = (expected_retcodes,)
  10.  
  11.     # we want the command to be a list, but accomodate when given a string
  12.     cmd = command
  13.     if type(cmd) == type('string'):
  14.         cmd = shlex.split(command)
  15.     print cmd
  16.     proc = subprocess.Popen(cmd,
  17.                             stdin  = stdin,
  18.                             stdout = subprocess.PIPE,
  19.                             stderr = subprocess.PIPE)
  20.  
  21.     out, err = proc.communicate()
  22.  
  23.     if proc.returncode not in expected_retcodes:
  24.         # when nothing gets to stderr, add stdout to Detail
  25.         if err.strip() == '':
  26.             err = out
  27.  
  28.         mesg  = 'Error [%d]: %s' % (proc.returncode, command)
  29.         mesg += '\nDetail: %s' % err
  30.         raise Exception, mesg
  31.  
  32.     return proc.returncode, out, err
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement