Incidentally, here's a simplified excerpt of Python code from a project
I maintain at my day job (https://launchpad.net/launchpad-buildd) which
could benefit from this, and also illustrates chaining the similar
env(1) as well:
import re
import subprocess
non_meta_re = re.compile(r'^[a-zA-Z0-9+,./:=@_-]+$')
def shell_escape(arg):
if non_meta_re.match(arg):
return arg
else:
return "'%s'" % arg.replace("'", "'\\''")
def run_build_command(chroot_path, args, env=None):
"""Run a build command in the chroot.
This is unpleasant because we need to run it in /build under sudo
chroot, and there's no way to do this without either a helper
program in the chroot or unpleasant quoting. We go for the
unpleasant quoting.
"""
args = [shell_escape(arg) for arg in args]
if env:
args = (
["env"] +
["%s=%s" % (key, shell_escape(value))
for key, value in env.items()] +
args)
command = "cd /build && %s" % " ".join(args)
subprocess.check_call(
["sudo", "chroot", chroot_path, "/bin/sh", "-c", command])
With chdir(1), this would become something like:
def run_build_command(chroot_path, args, env=None):
"""Run a build command in the chroot."""
if env:
args = (
["env"] +
["%s=%s" % (key, value) for key, value in env.items()] +
args)
subprocess.check_call(
["sudo", "chroot", chroot_path, "chdir", "/build"] + args)
--
Colin Watson [[email protected]]