commit: 5b7fbe02062796313ad094892f44aac73372f9f6 Author: Anthony G. Basile <blueness <AT> gentoo <DOT> org> AuthorDate: Fri Jul 10 02:04:37 2015 +0000 Commit: Anthony G. Basile <blueness <AT> gentoo <DOT> org> CommitDate: Fri Jul 10 02:04:37 2015 +0000 URL: https://gitweb.gentoo.org/proj/grss.git/commit/?id=5b7fbe02
grs/Execute.py: document and add logging to stderr. grs/Execute.py | 46 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/grs/Execute.py b/grs/Execute.py index 15fe562..f740924 100644 --- a/grs/Execute.py +++ b/grs/Execute.py @@ -4,16 +4,24 @@ import os import signal import shlex import subprocess +import sys from grs.Constants import CONST class Execute(): - """ doc here - more doc - """ + """ Execute a shell command """ def __init__(self, cmd, timeout = 1, extra_env = {}, failok = False, logfile = CONST.LOGFILE): - """ doc here - more doc + """ Execute a shell command. + + cmd - Simple string of the command to be execute as a + fork()-ed child. + timeout - The time in seconds to wait() on the child before + sending a SIGTERM. timeout = None means wait indefinitely. + extra_env - Dictionary of extra environment variables for the fork()-ed + child. Note that the child inherits all the env variables + of the grandparent shell in which grsrun/grsup was spawned. + logfile - A file to log output to. If logfile = None, then we log + to sys.stdout. """ def signalexit(): pid = os.getpid() @@ -25,11 +33,15 @@ class Execute(): except ProcessLookupError: pass - f = open(logfile, 'a') args = shlex.split(cmd) extra_env = dict(os.environ, **extra_env) - proc = subprocess.Popen(args, stdout=f, stderr=f, env=extra_env) + if logfile: + f = open(logfile, 'a') + proc = subprocess.Popen(args, stdout=f, stderr=f, env=extra_env) + else: + f = sys.stderr + proc = subprocess.Popen(args, env=extra_env) try: proc.wait(timeout) @@ -38,13 +50,19 @@ class Execute(): proc.kill() timed_out = True - rc = proc.returncode - if rc != 0: - f.write('EXIT CODE: %d\n' % rc) - if not failok: - signalexit() + if not timed_out: + # rc = None if we had a timeout + rc = proc.returncode + if rc: + f.write('EXIT CODE: %d\n' % rc) + if not failok: + signalexit() if timed_out: - f.write('TIMEOUT ERROR: %s\n' % cmd) + f.write('TIMEOUT ERROR: %s\n' % cmd) + if not failok: + signalexit() - f.close() + # Only close a logfile, don't close sys.stderr! + if logfile: + f.close()