Created
August 12, 2015 18:33
-
-
Save glennzw/2a8fac7379ffa4a36439 to your computer and use it in GitHub Desktop.
Run program's from Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def run_program(rcmd): | |
""" | |
Runs a program, and it's paramters (e.g. rcmd="ls -lh /var/www") | |
Returns output if successful, or None and logs error if not. | |
""" | |
cmd = shlex.split(rcmd) | |
executable = cmd[0] | |
executable_options=cmd[1:] | |
try: | |
proc = Popen(([executable] + executable_options), stdout=PIPE, stderr=PIPE) | |
response = proc.communicate() | |
response_stdout, response_stderr = response[0], response[1] | |
except OSError, e: | |
if e.errno == errno.ENOENT: | |
logging.debug( "Unable to locate '%s' program. Is it in your path?" % executable ) | |
return(-1, "Unable to locate '%s' program. Is it in your path?" % executable) | |
else: | |
logging.error( "O/S error occured when trying to run '%s': \"%s\"" % (executable, str(e)) ) | |
return(-1, "O/S error occured when trying to run '%s': \"%s\"" % (executable, str(e)) ) | |
except ValueError, e: | |
logging.debug( "Value error occured. Check your parameters." ) | |
else: | |
ret = proc.wait() | |
if ret != 0: | |
logging.debug( "Executable '%s' returned with the error: \"%s\"" %(executable,response_stderr) ) | |
return (ret,response_stderr.rstrip()) | |
else: | |
logging.debug( "Executable '%s' returned successfully. First line of response was \"%s\"" %(executable, response_stdout.split('\n')[0] )) | |
return (ret,response_stdout) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment