Simple wrapper around cmd.run_all
    log_msg can contain {0} for stderr
    :return: True or stdout, False if retcode wasn't exitcode
327720
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
    '''
    
    '''
    res = __salt__['cmd.run_all'](cmd)
    if res['retcode'] == exitcode:
        if res['stdout']:
            return res['stdout']
        else:
            return True

    if log_lvl is not None:
        log.log(LOG[log_lvl], log_msg, res['stderr'])
    return False
1114801
def check_output(params):
    
    popen = subprocess.Popen(params, shell=True, stderr=subprocess.STDOUT,
                             stdout=subprocess.PIPE)

    output, _ = popen.communicate()
    returncode = popen.poll()
    if returncode != 0:
        error = subprocess.CalledProcessError(returncode=returncode, cmd=params)
        error.output = output
        raise error
    return output
1220889
def check_output(*args, **kwargs):
    ''''''
    if hasattr(subprocess, 'check_output'):
        return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True,
                                       *args, **kwargs)
    else:
        process = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                   universal_newlines=True, **kwargs)
        output, _ = process.communicate()
        retcode = process.poll()
        if retcode:
            error = subprocess.CalledProcessError(retcode, args[0])
            error.output = output
            raise error
        return output
324729
def _cmd_run(cmd):
    '''
    
    '''
    cmd.insert(0, 'aptly')
    cmd_ret = __salt__['cmd.run_all'](cmd, ignore_retcode=True)

    if cmd_ret['retcode'] != 0:
        log.debug('Unable to execute command: %s\nError: %s', cmd,
                   cmd_ret['stderr'])

    return cmd_ret['stdout']
1252229
def exit(exit_code=0):
    

    LOGGER.debug("> {0} | Exiting current process!".format(__name__))

    LOGGER.debug("> Stopping logging handlers and logger!")
    for handler in LOGGER.handlers:
        foundations.verbose.remove_logging_handler(handler)

    sys.exit(exit_code)
1094937
def get_exit_code(self):
        
        args = shlex.split(self.cmd)

        proc = Popen(args, stdout=PIPE, stderr=PIPE)
        out, err = proc.communicate()
        out, err = out.decode("utf8"), err.decode("utf8")
        exitcode = proc.returncode
        #
        return exitcode, out, err
1247768
def run_command(cmd, redirect_output=True, check_exit_code=True):
    
    if redirect_output:
        stdout = subprocess.PIPE
    else:
        stdout = None
    proc = subprocess.Popen(cmd, cwd=ROOT, stdout=stdout)
    output = proc.communicate()[0]
    if check_exit_code and proc.returncode != 0:
        raise Exception('Command "%s" failed.\n%s' % (' '.join(cmd), output))
    return output
474286
def _check_result(self):
        '''
        
        '''
        if not self.__call_result:
            raise CommandExecutionError('No output result from Zypper?')

        self.exit_code = self.__call_result['retcode']
        if self._is_lock():
            return False

        if self._is_error():
            _error_msg = list()
            if not self._is_xml_mode():
                msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
                if msg:
                    _error_msg.append(msg)
            else:
                try:
                    doc = dom.parseString(self.__call_result['stdout'])
                except ExpatError as err:
                    log.error(err)
                    doc = None
                if doc:
                    msg_nodes = doc.getElementsByTagName('message')
                    for node in msg_nodes:
                        if node.getAttribute('type') == 'error':
                            _error_msg.append(node.childNodes[0].nodeValue)
                elif self.__call_result['stderr'].strip():
                    _error_msg.append(self.__call_result['stderr'].strip())
            self.error_msg = _error_msg
        return True
1208802
def signal(signal=None):
    '''
    
    '''
    valid_signals = ('start', 'reopen', 'stop', 'quit', 'reload')

    if signal not in valid_signals:
        return

    # Make sure you use the right arguments
    if signal == "start":
        arguments = ''
    else:
        arguments = ' -s {0}'.format(signal)
    cmd = __detect_os() + arguments
    out = __salt__['cmd.run_all'](cmd)

    # A non-zero return code means fail
    if out['retcode'] and out['stderr']:
        ret = out['stderr'].strip()
    # 'nginxctl configtest' returns 'Syntax OK' to stderr
    elif out['stderr']:
        ret = out['stderr'].strip()
    elif out['stdout']:
        ret = out['stdout'].strip()
    # No output for something like: nginxctl graceful
    else:
        ret = 'Command: "{0}" completed successfully!'.format(cmd)
    return ret
890702
def Exit(msg, code=1):
    
    print >> sys.stderr, msg
    sys.exit(code)
1153105
def _subprocess(cmd):
    '''
    
    '''

    log.debug('Running: "%s"', ' '.join(cmd))
    try:
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        ret = salt.utils.stringutils.to_unicode(proc.communicate()[0]).strip()
        retcode = proc.wait()

        if ret:
            return ret
        elif retcode != 1:
            return True
        else:
            return False
    except OSError as err:
        log.error(err)
        return False
879448
def error(self, message, code=1):
        
        sys.stderr.write(message)
        sys.exit(code)
281991
def cmd_ok(cmd):
     
    try:
        sp.check_call(cmd, stderr=sp.PIPE, stdout=sp.PIPE)
    except sp.CalledProcessError:
        # bwa gives return code of 1 with no argument
        pass
    except:
        sys.stderr.write("{} not found, skipping\n".format(cmd))
        return False
    return True
376387
def stderr_cm(self):
        
        with open(self._get_stderr_log(), 'a+') as fh:
            msg = '### {} ###\n'.format(self._datetime)
            fh.write(msg)
            fh.flush()

            try:
                yield fh
            except Exception as e:
                self._has_error = True
                fh.write(e.message)
                fh.flush()
                raise
499863
def check_last_exit_values(self,
	                           send,
	                           check_exit=True,
	                           expect=None,
	                           exit_values=None,
	                           retry=0,
	                           retbool=False):
		
		shutit = self.shutit
		expect = expect or self.default_expect
		if not self.check_exit or not check_exit:
			shutit.log('check_exit configured off, returning', level=logging.DEBUG)
			return True
		if exit_values is None:
			exit_values = ['0']
		if isinstance(exit_values, int):
			exit_values = [str(exit_values)]
		# Don't use send here (will mess up last_output)!
		# Space before "echo" here is sic - we don't need this to show up in bash history
		send_exit_code = ' echo EXIT_CODE:$?'
		shutit.log('Sending with sendline: ' + str(send_exit_code), level=logging.DEBUG)
		assert not self.sendline(ShutItSendSpec(self,
		                                        send=send_exit_code,
		                                        ignore_background=True)), shutit_util.print_debug()
		shutit.log('Expecting: ' + str(expect), level=logging.DEBUG)
		self.expect(expect,timeout=10)
		shutit.log('before: ' + str(self.pexpect_child.before), level=logging.DEBUG)
		res = shutit.match_string(str(self.pexpect_child.before), '^EXIT_CODE:([0-9][0-9]?[0-9]?)$')
		if res not in exit_values or res is None: # pragma: no cover
			res_str = res or str(res)
			shutit.log('shutit_pexpect_child.after: ' + str(self.pexpect_child.after), level=logging.DEBUG)
			shutit.log('Exit value from command: ' + str(send) + ' was:' + res_str, level=logging.DEBUG)
			msg = ('\nWARNING: command:\n' + send + '\nreturned unaccepted exit code: ' + res_str + '\nIf this is expected, pass in check_exit=False or an exit_values array into the send function call.')
			shutit.build['report'] += msg
			if retbool:
				return False
			elif retry == 1 and shutit_global.shutit_global_object.interactive >= 1:
				# This is a failure, so we pass in level=0
				shutit.pause_point(msg + '\n\nInteractive, so not retrying.\nPause point on exit_code != 0 (' + res_str + '). CTRL-C to quit', shutit_pexpect_child=self.pexpect_child, level=0)
			elif retry == 1:
				shutit.fail('Exit value from command\n' + send + '\nwas:\n' + res_str, throw_exception=False) # pragma: no cover
			else:
				return False
		return True
791361
def check_output(args):
    """"""
    log.debug('run: %s', args)
    out = subprocess.check_output(args=args).decode('utf-8')
    log.debug('out: %r', out)
    return out
819029
def succ(cmd, check_stderr=True, stdout=None, stderr=None):
    '''
    
    '''
    code, out, err = run(cmd)

    # Because we're raising error, sometimes we want to process stdout/stderr after catching error
    # so we're copying these outputs if required
    if stdout is not None:
        stdout[:] = out
    if stderr is not None:
        stderr[:] = err

    if code != 0:
        for l in out:
            print(l)
    assert code == 0, 'Return: {} {}\nStderr: {}'.format(code, cmd, err)
    if check_stderr:
        assert err == [], 'Error: {} {}'.format(err, code)
    return code, out, err