Run command line
763009
def main() -> None:
    """"""
    try:
        _real_main()
    except GuesslangError as error:
        LOGGER.critical("Failed: %s", error)
        sys.exit(-1)
    except KeyboardInterrupt:
        LOGGER.critical("Cancelled!")
        sys.exit(-2)
307679
def do_run(self,args):
        """"""
        parser = CommandArgumentParser("run")
        parser.add_argument('-R','--replace-key',dest='replaceKey',default=False,action='store_true',help="Replace the host's key. This is useful when AWS recycles an IP address you've seen before.")
        parser.add_argument('-Y','--keyscan',dest='keyscan',default=False,action='store_true',help="Perform a keyscan to avoid having to say 'yes' for a new host. Implies -R.")
        parser.add_argument('-ii','--ignore-host-key',dest='ignore-host-key',default=False,action='store_true',help='Ignore host key')
        parser.add_argument('-ne','--no-echo',dest='no-echo',default=False,action='store_true',help='Do not echo command')
        parser.add_argument(dest='command',nargs='+',help="Command to run on all hosts.") # consider adding a filter option later
        parser.add_argument('-v',dest='verbosity',default=0,action=VAction,nargs='?',help='Verbosity. The more instances, the more verbose');        
        parser.add_argument('-j',dest='jobs',type=int,default=1,help='Number of hosts to contact in parallel');
        parser.add_argument('-s',dest='skip',type=int,default=0,help='Skip this many hosts');
        parser.add_argument('-m',dest='macro',default=False,action='store_true',help='{command} is a series of macros to execute, not the actual command to run on the host');
        args = vars(parser.parse_args(args))

        replaceKey = args['replaceKey']
        keyscan = args['keyscan']
        verbosity = args['verbosity']
        jobs = args['jobs']
        skip = args['skip']
        ignoreHostKey = args['ignore-host-key']
        noEcho = args['no-echo']

        instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']
        instances = instances[skip:]
        # if replaceKey or keyscan:
        #     for instance in instances:
        #         stdplus.resetKnownHost(instance)

        if args['macro']:
            if len(args['command']) > 1:
                print("Only one macro may be specified with the -m switch.")
                return
            else:
                macro = args['command'][0]
                print("Macro:{}".format(macro))
                command = Config.config['ssh-macros'][macro]
        else:
            command = ' '.join(args['command'])
            
        Parallel(n_jobs=jobs)(
            delayed(ssh)(instance['InstanceId'],0,[],replaceKey,keyscan,False,verbosity,command,ignoreHostKey=ignoreHostKey,echoCommand=not noEcho,name="{}:{}: ".format(instance['index'],instance['InstanceId'])) for instance in instances
        )
566842
def run_command(*args)
      require 'tempfile'
      out = Tempfile.new('tty-screen')
      result = system(*args, out: out.path, err: File::NULL)
      return if result.nil?
      out.rewind
      out.read
    ensure
      out.close if out
    end
89703
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="rockfinder",
        defaultSettingsFile=True
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # CALL FUNCTIONS/OBJECTS

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/rockfinder/rockfinder.yaml"
        cmd = """open %(filepath)s""" % locals()
        p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        return

    if where and orbfitFlag:
        from rockfinder import orbfit_ephemeris
        eph = orbfit_ephemeris(
            log=log,
            objectId=objectId,
            mjd=mjd,
            obscode=obscode,
            settings=settings,
            verbose=extraFlag
        )
    else:
        from rockfinder import jpl_horizons_ephemeris
        eph = jpl_horizons_ephemeris(
            log=log,
            objectId=objectId,
            mjd=mjd,
            obscode=obscode,
            verbose=extraFlag
        )

    dataSet = list_of_dictionaries(
        log=log,
        listOfDictionaries=eph
    )
    # xfundamentals-render-list-of-dictionaries

    output = dataSet.table(filepath=None)
    if csv:
        output = dataSet.csv(filepath=None)
    elif json:
        output = dataSet.json(filepath=None)
    elif yaml:
        output = dataSet.yaml(filepath=None)
    elif md:
        output = dataSet.markdown(filepath=None)
    elif rst:
        output = dataSet.reST(filepath=None)

    print output

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
370944
def run(cmds)
      exit_status = 0
      puts bold("[Running]\n#{cmds.gsub(/^\s*/, '   ')}")
      $stdout.flush
      #puts cmds.split(/\n */).inspect
      cmds.split(/\n */).each do |cmd|
        next if cmd.empty?
        system(cmd.to_s) unless FalkorLib.config.debug
        exit_status = $?.exitstatus
      end
      exit_status
    end
1085408
def run():
    
    # setup the main parser and sub parsers
    parser = ArgumentParser(prog="law", description="The law command line tool.")
    sub_parsers = parser.add_subparsers(help="subcommands", dest="command")

    # add main arguments
    parser.add_argument("--version", "-V", action="version", version=law.__version__)

    # setup all progs
    mods = {}
    for prog in progs:
        mods[prog] = import_module("law.cli." + prog)
        mods[prog].setup_parser(sub_parsers)

    # parse args and dispatch execution
    if len(sys.argv) >= 2 and sys.argv[1] in forward_progs:
        args = parser.parse_args(sys.argv[1:3])
    else:
        args = parser.parse_args()

    if args.command:
        mods[args.command].execute(args)
    else:
        parser.print_help()
148542
def _run(self, command: List[str], notebook: Optional[str] = None) -> int:
        """"""
        if notebook is None:
            return Popen(command, cwd=self._build_dir).wait()
        cmd = Popen(command, cwd=self._build_dir, stdout=PIPE, stderr=STDOUT)
        while True:
            line = cmd.stdout.readline()
            if line == b'' and cmd.poll() is not None:
                return cmd.poll()
            print(line.decode('utf-8'), end='')
        raise Exception()
1331428
def run_command(self, cmd, history=True, new_prompt=True):
        """"""
        if not cmd:
            cmd = ''
        else:
            if history:
                self.add_to_history(cmd)
        if not self.multithreaded:
            if 'input' not in cmd:
                self.interpreter.stdin_write.write(
                                                to_binary_string(cmd + '\n'))
                self.interpreter.run_line()
                self.refresh.emit()
            else:
                self.write(_('In order to use commands like "raw_input" '
                             'or "input" run Spyder with the multithread '
                             'option (--multithread) from a system terminal'),
                           error=True)
        else:
            self.interpreter.stdin_write.write(to_binary_string(cmd + '\n'))
405299
def _run_cmd(cmd):
    '''
    
    '''
    ret = {}
    env_vars = {
        'KAPACITOR_URL': _get_url(),
        'KAPACITOR_UNSAFE_SSL': __salt__['config.option']('kapacitor.unsafe_ssl', 'false'),
    }
    result = __salt__['cmd.run_all'](cmd, env=env_vars)

    if result.get('stdout'):
        ret['stdout'] = result['stdout']
    if result.get('stderr'):
        ret['stderr'] = result['stderr']
    ret['success'] = result['retcode'] == 0

    return ret
576593
def runCommand(cmd, timeout=None, window=None):
    
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ''
    for line in p.stdout:
        line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
        output += line
        print(line)
        window.Refresh() if window else None        # yes, a 1-line if, so shoot me

    retval = p.wait(timeout)
    return (retval, output)
348087
def run(cmd, input=None, capture_output=False, check=False, quiet=False, **kwargs):
    """"""
    if input is not None:
        kwargs['stdin'] = subprocess.PIPE
    if capture_output:
        kwargs['stdout'] = kwargs['stderr'] = subprocess.PIPE

    try:
        proc = subprocess.Popen(cmd, startupinfo=get_startupinfo(), **kwargs)
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise ExecutableNotFound(cmd)
        else:
            raise

    out, err = proc.communicate(input)

    if not quiet and err:
        stderr_write_bytes(err, flush=True)
    if check and proc.returncode:
        raise CalledProcessError(proc.returncode, cmd, output=out, stderr=err)

    return out, err
756123
function runCommand(cmd, args, cb) {

	// set locale so we can be sure of consistency of command execution
	const env = extend(process.env, { LANG: 'en', LC_ALL: 'en', LC_MESSAGES: 'en' });

	const argArray = Array.isArray(args) ? args : args.split(' ');

	const s = spawn(cmd, argArray, {
		stdio: ['ignore', 'pipe', 'pipe'],
		env
	});

	let stdout = '';
	s.stdout.on('data', (data) => {
		stdout += data;
	});

	let stderr = '';
	s.stderr.on('data', (data) => {
		stderr += data;
	});

	s.on('error', (error) => {
		cb(error, null, stdout, stderr);
	});

	s.on('close', (code) => {
		cb(null, code, stdout, stderr);
	});
}
563005
def _runcmd(progargs, stdinput=None):
    '''
    
    '''
    stdin = None
    if stdinput is not None:
        assert(isinstance(stdinput, list))
        stdin=PIPE

    err = 0
    output = b''
    log_debug("Calling {} with input {}".format(' '.join(progargs), stdinput))
    try:
        p = Popen(progargs, shell=True, stdin=stdin, 
            stderr=STDOUT, stdout=PIPE, universal_newlines=True)
        if stdinput is not None:
            for cmd in stdinput:
                print(cmd, file=p.stdin)
            p.stdin.close()
        output = p.stdout.read()
        p.stdout.close()
        err = p.wait(timeout=1.0)
    except OSError as e:
        err = e.errno
        log_warn("Error calling {}: {}".format(progargs, e.stderror))
    except Exception as e:
        errstr = str(e)
        log_warn("Error calling {}: {}".format(progargs, errstr))
        err = -1
    log_debug("Result of command (errcode {}): {}".format(err, output))
    return err,output
401905
def run_command(cmd, *args):
    
    command = ' '.join((cmd, args))
    p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    return p.retcode, stdout, stderr
1367306
def _run_cli_process(cmd, shell=True):
        
        from subprocess import Popen, PIPE

        p = Popen(cmd, shell=shell, stdout=PIPE, stderr=PIPE)
        _stdout, _stderr = p.communicate()
        return _stdout, _stderr, p.returncode
1095274
def _run_cmd(cmd):
    """"""
    if not os.path.exists(cmd[0]):
        cmd[0] = shutil.which(cmd[0])
        assert cmd[0] is not None

    shebang_parts = parseshebang.parse(cmd[0])

    proc = subprocess.Popen(shebang_parts + cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    return {
        "stdout": stdout,
        "stderr": stderr,
        "code": proc.returncode
    }
1243759
def run_command(self, args=None, node_paths=None):
    """"""
    return command_gen(
      self.tool_installations,
      self.name,
      args=args,
      node_paths=node_paths
    )