Builds a shell command with various kwargs.
430517
def make_command(
    command,
    env=None,
    su_user=None,
    sudo=False,
    sudo_user=None,
    preserve_sudo_env=False,
):
    '''
    
    '''

    debug_meta = {}

    for key, value in (
        ('sudo', sudo),
        ('sudo_user', sudo_user),
        ('su_user', su_user),
        ('env', env),
    ):
        if value:
            debug_meta[key] = value

    logger.debug('Building command ({0}): {1}'.format(' '.join(
        '{0}: {1}'.format(key, value)
        for key, value in six.iteritems(debug_meta)
    ), command))

    # Use env & build our actual command
    if env:
        env_string = ' '.join([
            '{0}={1}'.format(key, value)
            for key, value in six.iteritems(env)
        ])
        command = 'export {0}; {1}'.format(env_string, command)

    # Quote the command as a string
    command = shlex_quote(command)

    # Switch user with su
    if su_user:
        command = 'su {0} -c {1}'.format(su_user, command)

    # Otherwise just sh wrap the command
    else:
        command = 'sh -c {0}'.format(command)

    # Use sudo (w/user?)
    if sudo:
        sudo_bits = ['sudo', '-H']

        if preserve_sudo_env:
            sudo_bits.append('-E')

        if sudo_user:
            sudo_bits.extend(('-u', sudo_user))

        command = '{0} {1}'.format(' '.join(sudo_bits), command)

    return command
565736
def exec_python(*args, **kwargs):
    
    cmdargs, kwargs = __wrap_python(args, kwargs)
    return exec_command(*cmdargs, **kwargs)
38912
def _add_two_argument_command(self, command, arg1, arg2):
        """"""
        self.lines.append("{} {} {}".format(command, arg1, arg2))
1004249
def shell(state, host, commands, chdir=None):
    '''
    
    '''

    # Ensure we have a list
    if isinstance(commands, six.string_types):
        commands = [commands]

    for command in commands:
        if chdir:
            yield 'cd {0} && ({1})'.format(chdir, command)
        else:
            yield command
599402
def process_kwargs(obj, kwargs):
    '''
    
    '''
    with Modules() as m:
        kwargs = m.kwargs(obj, kwargs)
    return kwargs
577491
def do_shell(self, args: argparse.Namespace) -> None:
        """"""
        import subprocess

        # Create a list of arguments to shell
        tokens = [args.command] + args.command_args

        # Support expanding ~ in quoted paths
        for index, _ in enumerate(tokens):
            if tokens[index]:
                # Check if the token is quoted. Since parsing already passed, there isn't
                # an unclosed quote. So we only need to check the first character.
                first_char = tokens[index][0]
                if first_char in constants.QUOTES:
                    tokens[index] = utils.strip_quotes(tokens[index])

                tokens[index] = os.path.expanduser(tokens[index])

                # Restore the quotes
                if first_char in constants.QUOTES:
                    tokens[index] = first_char + tokens[index] + first_char

        expanded_command = ' '.join(tokens)

        # Prevent KeyboardInterrupts while in the shell process. The shell process will
        # still receive the SIGINT since it is in the same process group as us.
        with self.sigint_protection:
            # For any stream that is a StdSim, we will use a pipe so we can capture its output
            proc = subprocess.Popen(expanded_command,
                                    stdout=subprocess.PIPE if isinstance(self.stdout, utils.StdSim) else self.stdout,
                                    stderr=subprocess.PIPE if isinstance(sys.stderr, utils.StdSim) else sys.stderr,
                                    shell=True)

            proc_reader = utils.ProcReader(proc, self.stdout, sys.stderr)
            proc_reader.wait()
701532
def shell_exec(command):
    """"""
    out = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
    return out.decode('utf-8')
95992
def shell_exec(command, **kwargs): # from gitapi.py
  
  proc = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE, **kwargs)

  out, err = [x.decode("utf-8") for x in  proc.communicate()]

  return {'out': out, 'err': err, 'code': proc.returncode}
679494
def _expand_args(command):
    """"""

    # Prepare arguments.
    if isinstance(command, STR_TYPES):
        if sys.version_info[0] == 2:
            splitter = shlex.shlex(command.encode("utf-8"))
        elif sys.version_info[0] == 3:
            splitter = shlex.shlex(command)
        else:
            splitter = shlex.shlex(command.encode("utf-8"))
        splitter.whitespace = "|"
        splitter.whitespace_split = True
        command = []

        while True:
            token = splitter.get_token()
            if token:
                command.append(token)
            else:
                break

        command = list(map(shlex.split, command))

    return command
1208600
def shell_call(self, shellcmd):
        """"""
        return(subprocess.call(self.shellsetup + shellcmd, shell=True))
1271777
def _build_arguments(self):
        
        self._parser.add_argument(
            '--attach',
            type=bool,
            required=False,
            default=False,
            help="Attach to containers output?"
        )

        self._parser.add_argument(
            '--clean',
            type=bool,
            required=False,
            default=False,
            help="clean up everything that was created by freight forwarder at the end."
        )

        self._parser.add_argument(
            '--configs',
            type=bool,
            required=False,
            default=False,
            help="Would you like to inject configuration files?"
        )

        self._parser.add_argument(
            '-e', '--env',
            required=False,
            type=str,
            action='append',
            default=None,
            help='environment variables to create in the container at run time.'
        )

        self._parser.add_argument(
            '--test',
            type=bool,
            required=False,
            default=False,
            help="Run tests."
        )

        self._parser.add_argument(
            '--use-cache',
            required=False,
            action='store_true',
            default=False,
            help='Allow build to use cached image layers.'
        )
254595
def buildCommand(self,fileName,count,args):
        
        # Escape all placeholders in the file path:
	fileNameWithPath = self.escapePlaceholders(fileName)

        # The command is split into 'parts', which are separated by blank spaces:
        commandParts = args.command.split(' ')
        processedParts = []
        # Each part of the command is processed separately:
        for part in commandParts:
            processedParts.append(self.buildPart(part,fileNameWithPath,count,args))
        # The parts are put together at the end and the new command is returned:
        return self.unescapePlaceholders(' '.join(processedParts))
100454
def shell(args):
    "  "
    print
    print "# Makesite integration "
    print "# ==================== "
    print "export MAKESITE_HOME=%s" % args.path
    print "source %s" % op.join(settings.BASEDIR, 'shell.sh')
    print
648096
def pop_op_kwargs(state, kwargs):
    '''
    
    '''

    meta_kwargs = state.deploy_kwargs or {}

    def get_kwarg(key, default=None):
        return kwargs.pop(key, meta_kwargs.get(key, default))

    # Get the env for this host: config env followed by command-level env
    env = state.config.ENV.copy()
    env.update(get_kwarg('env', {}))

    hosts = get_kwarg('hosts')
    hosts = ensure_host_list(hosts, inventory=state.inventory)

    # Filter out any hosts not in the meta kwargs (nested support)
    if meta_kwargs.get('hosts') is not None:
        hosts = [
            host for host in hosts
            if host in meta_kwargs['hosts']
        ]

    return {
        # ENVars for commands in this operation
        'env': env,
        # Hosts to limit the op to
        'hosts': hosts,
        # When to limit the op (default always)
        'when': get_kwarg('when', True),
        # Locally & globally configurable
        'sudo': get_kwarg('sudo', state.config.SUDO),
        'sudo_user': get_kwarg('sudo_user', state.config.SUDO_USER),
        'su_user': get_kwarg('su_user', state.config.SU_USER),
        # Whether to preserve ENVars when sudoing (eg SSH forward agent socket)
        'preserve_sudo_env': get_kwarg(
            'preserve_sudo_env', state.config.PRESERVE_SUDO_ENV,
        ),
        # Ignore any errors during this operation
        'ignore_errors': get_kwarg(
            'ignore_errors', state.config.IGNORE_ERRORS,
        ),
        # Timeout on running the command
        'timeout': get_kwarg('timeout'),
        # Get a PTY before executing commands
        'get_pty': get_kwarg('get_pty', False),
        # Forces serial mode for this operation (--serial for one op)
        'serial': get_kwarg('serial', False),
        # Only runs this operation once
        'run_once': get_kwarg('run_once', False),
        # Execute in batches of X hosts rather than all at once
        'parallel': get_kwarg('parallel'),
        # Callbacks
        'on_success': get_kwarg('on_success'),
        'on_error': get_kwarg('on_error'),
        # Operation hash
        'op': get_kwarg('op'),
    }
391983
def pipe_shell_cmds(shell_CMDs):
    '''
        
    '''
    len = shell_CMDs.__len__()
    p = {}
    p[1] = subprocess.Popen(shlex.split(shell_CMDs[1]), stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    for i in range(2,len):
        p[i] = subprocess.Popen(shlex.split(shell_CMDs[i]), stdin=p[i-1].stdout, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    if(len > 1):
        p[len] = subprocess.Popen(shlex.split(shell_CMDs[len]), stdin=p[len-1].stdout, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    result = p[len].communicate()
    if(len > 1):
        for i in range(2,len+1):
            returncode = p[i].wait()
    else:
        returncode = p[len].wait()
    return(result)
686130
def cli(ctx, env):
    """"""
    env.out("Welcome to the SoftLayer shell.")
    env.out("")

    formatter = formatting.HelpFormatter()
    commands = []
    shell_commands = []
    for name in cli_core.cli.list_commands(ctx):
        command = cli_core.cli.get_command(ctx, name)
        if command.short_help is None:
            command.short_help = command.help
        details = (name, command.short_help)
        if name in dict(routes.ALL_ROUTES):
            shell_commands.append(details)
        else:
            commands.append(details)

    with formatter.section('Shell Commands'):
        formatter.write_dl(shell_commands)

    with formatter.section('Commands'):
        formatter.write_dl(commands)

    for line in formatter.buffer:
        env.out(line, newline=False)
1263099
def invoke_command (self, cmd, args, **kwargs):
        """"""
        new_kwargs = kwargs.copy ()
        new_kwargs['argv0'] = kwargs['argv0'] + ' ' + cmd.name
        new_kwargs['parent'] = self
        new_kwargs['parent_kwargs'] = kwargs
        return cmd.invoke_with_usage (args, **new_kwargs)