<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def run_in_buildenv( self, buildenv_target_name: str, cmd: list, cmd_env: dict=None, work_dir: str=None, auto_uid: bool=True, runtime: str=None, **kwargs):
 """Run a command in a named BuildEnv Docker image. :param buildenv_target_name: A named Docker image target in which the command should be run. :param cmd: The command to run, as you'd pass to subprocess.run() :param cmd_env: A dictionary of environment variables for the command. :param work_dir: A different work dir to run in. Either absolute path, or relative to project root. :param auto_uid: Whether to run as the active uid:gid, or as root. :param kwargs: Extra keyword arguments that are passed to the subprocess.run() call that runs the BuildEnv container (for, e.g. timeout arg, stdout/err redirection, etc.) :raises KeyError: If named BuildEnv is not a registered BuildEnv image """

        buildenv_target = self.targets[buildenv_target_name]
        # TODO(itamar): Assert that buildenv_target is up to date
        redirection = any(
            stream_key in kwargs
            for stream_key in ('stdin', 'stdout', 'stderr', 'input'))
        docker_run = ['docker', 'run']
        # if not self.conf.non_interactive:
        #     docker_run.append('-i')
        if not redirection:
            docker_run.append('-t')
        project_vol = (self.conf.docker_volume if self.conf.docker_volume else
                       self.conf.project_root)
        container_work_dir = PurePath('/project')
        if work_dir:
            container_work_dir /= work_dir
        if runtime:
            docker_run.extend([
                '--runtime', runtime,
            ])

        docker_run.extend([
            '--rm',
            '-v', project_vol + ':/project',
            # TODO: windows containers?
            '-w', container_work_dir.as_posix(),
        ])
        if cmd_env:
            for key, value in cmd_env.items():
                # TODO(itamar): escaping
                docker_run.extend(['-e', '{}={}'.format(key, value)])
        if platform.system() == 'Linux' and auto_uid:
            # Fix permissions for bind-mounted project dir
            # The fix is not needed when using Docker For Mac / Windows,
            # because it is somehow taken care of by the sharing mechanics
            docker_run.extend([
                '-u', '{}:{}'.format(os.getuid(), os.getgid()),
                '-v', '/etc/shadow:/etc/shadow:ro',
                '-v', '/etc/group:/etc/group:ro',
                '-v', '/etc/passwd:/etc/passwd:ro',
                '-v', '/etc/sudoers:/etc/sudoers:ro',
            ])
        docker_run.append(format_qualified_image_name(buildenv_target))
        docker_run.extend(cmd)
        logger.info('Running command in build env "{}" using command {}',
                    buildenv_target_name, docker_run)
        # TODO: Consider changing the PIPEs to temp files.
        if 'stderr' not in kwargs:
            kwargs['stderr'] = PIPE
        if 'stdout' not in kwargs:
            kwargs['stdout'] = PIPE
        result = run(docker_run, check=True, **kwargs)

        # TODO(Dana): Understand what is the right enconding and remove the
        # try except
        if kwargs['stdout'] is PIPE:
            try:
                sys.stdout.write(result.stdout.decode('utf-8'))
            except UnicodeEncodeError as e:
                sys.stderr.write('tried writing the stdout of {},\n but it '
                                 'has a problematic character:\n {}\n'
                                 'hex dump of stdout:\n{}\n'
                                 .format(docker_run, str(e), codecs.encode(
                                    result.stdout, 'hex').decode('utf8')))
        if kwargs['stderr'] is PIPE:
            try:
                sys.stderr.write(result.stderr.decode('utf-8'))
            except UnicodeEncodeError as e:
                sys.stderr.write('tried writing the stderr of {},\n but it '
                                 'has a problematic character:\n {}\n'
                                 'hex dump of stderr:\n{}\n'
                                 .format(docker_run, str(e), codecs.encode(
                                    result.stderr, 'hex').decode('utf8')))
        return result