From bf4daac98ca3ff323757cefa3e0b2eaa85612e66 Mon Sep 17 00:00:00 2001 From: Guido Trotter <ultrotter@google.com> Date: Fri, 19 Feb 2010 15:35:37 +0000 Subject: [PATCH] Add reset_env option to RunCmd This allows to run a command with only the passed in environment, rather than just updating the default one with it. Now with unit testing. Signed-off-by: Guido Trotter <ultrotter@google.com> Reviewed-by: Iustin Pop <iustin@google.com> --- lib/utils.py | 14 ++++++++++---- test/ganeti.utils_unittest.py | 4 ++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/utils.py b/lib/utils.py index c8a22c9e2..261c52c2b 100644 --- a/lib/utils.py +++ b/lib/utils.py @@ -118,13 +118,13 @@ class RunResult(object): output = property(_GetOutput, None, None, "Return full output") -def RunCmd(cmd, env=None, output=None, cwd='/'): +def RunCmd(cmd, env=None, output=None, cwd='/', reset_env=False): """Execute a (shell) command. The command should not read from its standard input, as it will be closed. - @type cmd: string or list + @type cmd: string or list @param cmd: Command to run @type env: dict @param env: Additional environment @@ -135,6 +135,8 @@ def RunCmd(cmd, env=None, output=None, cwd='/'): @type cwd: string @param cwd: if specified, will be used as the working directory for the command; the default will be / + @type reset_env: boolean + @param reset_env: whether to reset or keep the default os environment @rtype: L{RunResult} @return: RunResult instance @raise errors.ProgrammerError: if we call this when forks are disabled @@ -152,8 +154,12 @@ def RunCmd(cmd, env=None, output=None, cwd='/'): shell = True logging.debug("RunCmd '%s'", strcmd) - cmd_env = os.environ.copy() - cmd_env["LC_ALL"] = "C" + if not reset_env: + cmd_env = os.environ.copy() + cmd_env["LC_ALL"] = "C" + else: + cmd_env = {} + if env is not None: cmd_env.update(env) diff --git a/test/ganeti.utils_unittest.py b/test/ganeti.utils_unittest.py index b6fed9347..906aecabf 100755 --- a/test/ganeti.utils_unittest.py +++ b/test/ganeti.utils_unittest.py @@ -231,6 +231,10 @@ class TestRunCmd(testutils.GanetiTestCase): cwd = os.getcwd() self.failUnlessEqual(RunCmd(["pwd"], cwd=cwd).stdout.strip(), cwd) + def testResetEnv(self): + """Test environment reset functionality""" + self.failUnlessEqual(RunCmd(["env"], reset_env=True).stdout.strip(), "") + class TestRemoveFile(unittest.TestCase): """Test case for the RemoveFile function""" -- GitLab