diff options
author | Lars Wirzenius <liw@liw.fi> | 2011-10-03 09:51:52 +0100 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2011-10-03 09:51:52 +0100 |
commit | 60768275cc746890b826b240eb0d6d04a6b9d046 (patch) | |
tree | f255b40a1f5f936624e7fea8d4d67e67ef9ac749 /morphlib | |
parent | ae0c04d3c10fa3e5ff91f387a25d1903a1b2c5a8 (diff) | |
download | morph-60768275cc746890b826b240eb0d6d04a6b9d046.tar.gz |
Make Execute.run and .runv be able to easily run commands as root.
Diffstat (limited to 'morphlib')
-rw-r--r-- | morphlib/execute.py | 11 | ||||
-rw-r--r-- | morphlib/execute_tests.py | 6 |
2 files changed, 14 insertions, 3 deletions
diff --git a/morphlib/execute.py b/morphlib/execute.py index cd2cc79a..18030ccc 100644 --- a/morphlib/execute.py +++ b/morphlib/execute.py @@ -38,7 +38,7 @@ class Execute(object): def _setup_env(self): self.env = dict(os.environ) - def run(self, commands): + def run(self, commands, as_root=False): '''Execute a list of commands. If a command fails (returns non-zero exit code), the rest are @@ -49,7 +49,10 @@ class Execute(object): stdouts = [] for command in commands: self.msg('# %s' % command) - p = subprocess.Popen([command], shell=True, + argv = ['sh', '-c', command] + if as_root: + argv = ['fakeroot'] + argv + p = subprocess.Popen(argv, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=self.env, @@ -64,7 +67,7 @@ class Execute(object): stdouts.append(out) return stdouts - def runv(self, argv): + def runv(self, argv, as_root=False): '''Run a command given as a list of argv elements. Return standard output. Raise ``CommandFailure`` if the command @@ -72,6 +75,8 @@ class Execute(object): ''' + if as_root: + argv = ['fakeroot'] + argv self.msg('# %s' % ' '.join(argv)) p = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.dirname) diff --git a/morphlib/execute_tests.py b/morphlib/execute_tests.py index dffc5a7f..2aedcd7a 100644 --- a/morphlib/execute_tests.py +++ b/morphlib/execute_tests.py @@ -52,3 +52,9 @@ class ExecuteTests(unittest.TestCase): def test_runv_sets_working_directory(self): self.assertEqual(self.e.runv(['pwd']), '/\n') + def test_runs_as_root_when_requested(self): + self.assertEqual(self.e.run(['id -u'], as_root=True), ['0\n']) + + def test_runvs_as_root_when_requested(self): + self.assertEqual(self.e.runv(['id', '-u'], as_root=True), '0\n') + |