Run the given subprocess command in a coroutine.

  Args:
    *cmd: the command to run and its arguments.

  Returns:
    The output that the command wrote to stdout.

  Raises:
    RuntimeError: if the command returns a non-zero result.
559032
async def checked_run(*cmd):
  

  # Start the subprocess.
  logging.info('Running: %s', expand_cmd_str(cmd))
  with logged_timer('{} finished'.format(get_cmd_name(cmd))):
    p = await asyncio.create_subprocess_exec(
        *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)

    # Stream output from the process stdout.
    chunks = []
    while True:
      chunk = await p.stdout.read(16 * 1024)
      if not chunk:
        break
      chunks.append(chunk)

    # Wait for the process to finish, check it was successful & build stdout.
    await p.wait()
    stdout = b''.join(chunks).decode()[:-1]
    if p.returncode:
      raise RuntimeError('Return code {} from process: {}\n{}'.format(
          p.returncode, expand_cmd_str(cmd), stdout))

    return stdout
339293
def run_command(
        cls,
        cmd,  # type: List[str]
        show_stdout=True,  # type: bool
        cwd=None,  # type: Optional[str]
        on_returncode='raise',  # type: str
        extra_ok_returncodes=None,  # type: Optional[Iterable[int]]
        command_desc=None,  # type: Optional[str]
        extra_environ=None,  # type: Optional[Mapping[str, Any]]
        spinner=None  # type: Optional[SpinnerInterface]
    ):
        # type: (...) -> Optional[Text]
        
        cmd = [cls.name] + cmd
        try:
            return call_subprocess(cmd, show_stdout, cwd,
                                   on_returncode=on_returncode,
                                   extra_ok_returncodes=extra_ok_returncodes,
                                   command_desc=command_desc,
                                   extra_environ=extra_environ,
                                   unset_environ=cls.unset_environ,
                                   spinner=spinner)
        except OSError as e:
            # errno.ENOENT = no such file or directory
            # In other words, the VCS executable isn't available
            if e.errno == errno.ENOENT:
                raise BadCommand(
                    'Cannot find command %r - do you have '
                    '%r installed and in your '
                    'PATH?' % (cls.name, cls.name))
            else:
                raise
39584
def run(self):
        

        async def run_command():
            try:
                self.result = self.command(
                    context=self.context,
                    **self.kwargs
                )
            except Exception as error:
                self.exception = error
                print(error)
                import traceback
                traceback.print_exc()
                import sys
                self.context.response.fail(
                    code='COMMAND_EXECUTION_ERROR',
                    message='Failed to execute command due to internal error',
                    error=error
                ).console(
                    whitespace=1
                )

        self._has_started = True
        self._loop = asyncio.new_event_loop()
        self._loop.run_until_complete(run_command())
        self._loop.close()
        self._loop = None
        self.completed_at = datetime.utcnow()
217445
def execute(cmd, cwd=None):
    
    try:
        lines = subprocess \
            .check_output(cmd, cwd=cwd, stderr=DEVNULL) \
            .splitlines()
    except subprocess.CalledProcessError:
        return None
    else:
        if lines:
            return decode(lines[0].strip())
        else:
            return None
1196881
def run(cmd):
    

    status, output = commands.getstatusoutput(cmd)
    if status:
        print(output)
    return status == 0
1114988
def run(self, instream=sys.stdin):
        
        sys.stdout.write(self.prompt)
        sys.stdout.flush()
        while True:
            line = instream.readline()
            try:
                self.exec_cmd(line)
            except Exception as e:
                self.errfun(e)

            sys.stdout.write(self.prompt)
            sys.stdout.flush()
1140647
def _exec(cmd):
        
        process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

        # pylint: disable=unexpected-keyword-arg
        (stdout, stderr) = process.communicate(timeout=defaults.DEFAULT_VCS_TIMEOUT)

        return process.returncode, stdout.decode(), stderr.decode()
826400
def call_command(self, cmd, *argv):
        
        parser = self.get_parser()
        args = [cmd] + list(argv)
        namespace = parser.parse_args(args)
        self.run_command(namespace)
1185352
def run_command(cmd):
    
    child = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    out = [s.decode("utf-8").strip() for s in child.stdout]
    err = [s.decode("utf-8").strip() for s in child.stderr]
    w = child.wait()
    return os.WEXITSTATUS(w), out, err
463008
def run_command_orig(cmd):
    
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    if process.returncode == 0:
        os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
    else:
        raise BadRCError("Bad rc (%s) for cmd '%s': %s" % (process.returncode, cmd, stdout + stderr))
    return stdout
1321803
def run_command(args, cwd = None, shell = False, timeout = None, env = None):
    '''
    
    '''
    from subprocess import PIPE, Popen
    from StringIO import StringIO
    import fcntl, os, signal
    p = Popen(args, shell = shell, cwd = cwd, stdout = PIPE, stderr = PIPE, env = env)
    tstart = time.time()
    buf = StringIO()

    # try to make it non-blocking
    try:
        fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
    except Exception:
        pass

    while True:
        time.sleep(0.1)
        retcode = p.poll()
        try:
            buf.write(p.stdout.read())
        except Exception:
            pass
        if retcode is not None:
            break
        if timeout is not None and time.time() > tstart + timeout:
            print("timeout in process %u" % p.pid)
            try: 
                os.kill(p.pid, signal.SIGKILL)
            except OSError:
                pass
            p.wait()
    return buf.getvalue()
1065408
def run(self, cmd):
        """"""
        print datetime.datetime.now()
        output = subprocess.Popen(cmd, shell=True)
        output = output.communicate()[0]
        print output
545192
def run_cmd(self, cmd, cwd=None, extra_env=None):
        
        all_output = []
        cmd_parts = []

        for part in cmd:
            if len(part) > 45:
                part = part[:20] + "..." + part[-20:]
            if ' ' in part or '\n' in part or '"' in part or "'" in part:
                part = '"%s"' % part.replace('"', '\\"')
            cmd_parts.append(part)
        cmd_desc = ' '.join(cmd_parts)
        logger.debug(" ** Running command %s" % cmd_desc)

        # output
        stdout = subprocess.PIPE

        # env
        if extra_env:
            env = os.environ.copy()
            if extra_env:
                env.update(extra_env)
        else:
            env = None

        # execute
        try:
            proc = subprocess.Popen(
                [' '.join(cmd)], stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
                cwd=cwd, env=env, shell=True)
        except Exception:
            e = sys.exc_info()[1]
            logger.error("Error %s while executing command %s" % (e, cmd_desc))
            raise

        stdout = proc.stdout
        while stdout:
            line = stdout.readline()
            if not line:
                break
            line = line.rstrip()
            all_output.append(line)
            logger.info(line)
        proc.wait()

        # error handler
        if proc.returncode:
            for s in all_output:
                logger.critical(s)
            raise OSError("Command %s failed with error code %s"
                % (cmd_desc, proc.returncode))

        return proc.returncode, all_output
999389
def run(cmd):
    """"""
    print("Preparing the following cmd:")
    cmd = prepare_subprocess_cmd(cmd)
    print("Running the following cmd:")
    print('\n'.join(cmd))
    return subprocess.run(cmd, stdout=sys.stdout, stderr=sys.stderr)
164384
async def runCmdLine(self, line):
        '''
        

        '''
        opts = self.getCmdOpts(line)
        return await self.runCmdOpts(opts)
707785
def run(self, cmd=None):
		
		diagnostics.prefix.append(self.name)

		if not cmd:
			cmd = self.cmd

		stderr = os.path.abspath(self.name + '.log')
		self.args.append('2>>'+stderr)

		if self.pipe:
			self.args += ('|', self.pipe, '2>>'+stderr)

		# Write to a stdout file if it was set by the derived class.
		# Otherwise, stdout and stderr will be combined into the log file.
		if self.stdout:
			stdout = os.path.abspath(self.stdout)
			self.args.append('1>'+stdout)
			diagnostics.log('stdout', stdout)
		elif self.stdout_append:
			stdout = os.path.abspath(self.stdout_append)
			self.args.append('1>>'+stdout)
			diagnostics.log('stdout', stdout)
		else:
			self.args.append('1>>'+stderr)

		# Print timestamp to log
		open(stderr, 'a').write("[biolite] timestamp=%s\n" % utils.timestamp())
		diagnostics.log('log', stderr)

		cmd = ' '.join(chain(cmd, map(str, self.args)))
		diagnostics.log('command', cmd)

		start = time.time()
		save_cwd = os.getcwd()
		try:
			os.chdir(self.cwd)
			spawn_pid = os.spawnle(os.P_NOWAIT, self.shell, self.shell, '-c', cmd, self.env)
			wait_pid, retcode, rusage = os.wait4(spawn_pid, 0)
			if wait_pid != spawn_pid:
				utils.die("could not wait for process %d: got %d" % (spawn_pid, wait_pid))
			os.chdir(save_cwd)
		except OSError as e:
			utils.info(e)
			utils.die("could not run wrapper for command:\n%s" % cmd)
			#utils.failed_executable(exe, e)

		elapsed = time.time() - start
		retcode = os.WEXITSTATUS(retcode)

		if (self.return_ok is not None) and (self.return_ok != retcode):
			# Give some context to the non-zero return.
			if os.path.isfile(stderr):
				subprocess.call(['tail', '-3', stderr])
			utils.die("non-zero return (%d) from command:\n%s" % (retcode, cmd))

		# Log profile.
		diagnostics.prefix.append('profile')
		diagnostics.log('name', self.name)
		diagnostics.log('return', retcode)
		diagnostics.log('walltime', elapsed)
		diagnostics.log('usertime', rusage.ru_utime)
		diagnostics.log('systime', rusage.ru_stime)
		if config.uname == 'Darwin':
			diagnostics.log('maxrss', rusage.ru_maxrss / 1024)
		else:
			diagnostics.log('maxrss', rusage.ru_maxrss)
		diagnostics.prefix.pop()

		# Reverse any output patterns, since they will be matched against
		# program output from the last line backward.
		if self.output_patterns:
			self.output_patterns.reverse()

		diagnostics.log_program_output(stderr, self.output_patterns)
		diagnostics.prefix.pop()
1247558
def run(self, command, options, pipe=False, get_stdout=False, memscale=None):
        
        cl = self.cl_picard(command, options, memscale=memscale)
        if pipe:
            subprocess.Popen(cl)
        elif get_stdout:
            p = subprocess.Popen(cl, stdout=subprocess.PIPE)
            stdout = p.stdout.read()
            p.wait()
            p.stdout.close()
            return stdout
        else:
            do.run(cl, "Picard {0}".format(command), None)