Inovke editor command in a shell

 @raise [TTY::CommandInvocationError]

 @api private
512397
def open
      status = system(env, *Shellwords.split(command_path))
      return status if status
      fail CommandInvocationError,
           "`#{command_path}` failed with status: #{$? ? $?.exitstatus : nil}"
    end
412183
def text(*)
      if options[:help]
        invoke :help, ['text']
      elsif options.empty?
        invoke :help
      else
        require_relative 'commands/text'
        RubyEdit::Commands::Text.new(options).execute
      end
    end
809465
def _run_command(self, command):
        
        try:
            my_result = call(command, shell=True)
            del my_result
        except CalledProcessError as e:
            LOGGER.exception('Running command failed %s' % command)
            message = (
                'Error while executing the following shell '
                'command: %s\nError message: %s' % (command, str(e)))
            # shameless hack - see https://github.com/AIFDR/inasafe/issues/141
            if sys.platform == 'darwin':  # Mac OS X
                if 'Errno 4' in str(e):
                    # continue as the error seems to be non critical
                    pass
                else:
                    raise Exception(message)
            else:
                raise Exception(message)
730759
def runCommand(command, silent=False, shell=False):
    
    splits = shlex.split(command)
    runCommandSplits(splits, silent=silent, shell=shell)
584670
def process_shell_command
      command_line.set_prompt ':!'
      cmd = command_line.get_command(prompt: ':!')[1..-1]
      execute_external_command pause: true do
        system cmd
      end
    rescue Interrupt
    ensure
      command_line.clear
      command_line.noutrefresh
    end
884508
private String openTextEditor() throws IOException, InterruptedException {
        String editor = Optional.ofNullable(System.getenv().get("EDITOR")).orElse(EDITOR_DEFAULT);
        File tempFile = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value() + EDITOR_FILE);
        tempFile.createNewFile();

        // Run the editor, pipe input into and out of tty so we can provide the input/output to the editor via Graql
        ProcessBuilder builder = new ProcessBuilder(
                "/bin/bash", "-c",
                editor + " </dev/tty >/dev/tty " + tempFile.getAbsolutePath()
        );

        builder.start().waitFor();
        return String.join("\n", Files.readAllLines(tempFile.toPath()));
    }
216960
def execute(node, arguments)  ## We'll add in arguments later
      if run_as_pseudo_tty?
        node.pseudo_tty command
      else
        node.run command
      end
    rescue Interrupt
      puts "\nExiting gracefully from interrupt\n".warning
    end
1162796
function startCmdEditor (config, is_skip_header) {

	if (!is_skip_header) {
		console.log(colors.bold('--------------- Command Editor ---------------'));
	}

	// Show a prompt for choose the mode
	var promise = inquirer.prompt([{
		type: 'list',
		name: 'mode',
		message: 'What you want to do ?',
		choices: [
			'Show commands list', 'Add new command', 'Edit command', 'Delete command'
		]
	}]);

	promise.then(function (answer) {

		var mode = answer.mode;
		var promise = null;

		if (mode == 'Add new command') {
			promise = addCommandOnCmdEditor(config);
		} else if (mode == 'Edit command') {
			promise = editCommandOnCmdEditor(config);
		} else if (mode == 'Delete command') {
			promise = deleteCommandOnCmdEditor(config);
		} else if (mode == 'Show commands list') {
			promise = showCommandsOnCmdEditor(config);
		}

		if (!promise) {
			startCmdEditor(config, true);
			return;
		}

		promise.then(function () {
			startCmdEditor(config, true);
		});

	});

}
666718
def shell(command, **kwargs):
    
    b_stdoutflush       = False
    b_stderrflush       = False
    b_waitForChild      = True
    for key, val in kwargs.items():
        if key == 'stdoutflush':        b_stdoutflush   = val
        if key == 'stderrflush':        b_stderrflush   = val
        if key == 'waitForChild':       b_waitForChild  = val
    child = popen2.Popen3(command, 1) # capture stdout and stderr from command
    child.tochild.close()             # don't need to talk to child
    outfile = child.fromchild
    outfd = outfile.fileno()
    errfile = child.childerr
    errfd = errfile.fileno()
    makeNonBlocking(outfd)            # don't deadlock!
    makeNonBlocking(errfd)
    outdata = errdata = ''
    outeof = erreof = 0
    while b_waitForChild:
        ready = select.select([outfd,errfd],[],[]) # wait for input
        if outfd in ready[0]:
            outchunk = outfile.read()
            if b_stdoutflush: sys.stdout.write(outchunk)
            if outchunk == '': outeof = 1
            outdata = outdata + outchunk
        if errfd in ready[0]:
            errchunk = errfile.read()
            if b_stderrflush: sys.stderr.write(errchunk)
            if errchunk == '': erreof = 1
            errdata = errdata + errchunk
        if outeof and erreof: break
        select.select([],[],[],.1) # give a little time for buffers to fill
    err = child.wait()
    return outdata, errdata, err
1210747
def inside(&block)
      if COOKBOOK_COMMANDS.any? { |c| command =~ /#{c}/ }
        Strainer.ui.debug "Detected '#{command}' should be run from inside the cookbook"
        inside_cookbook(&block)
      else
        Strainer.ui.debug "Detected '#{command}' should be run from inside the sandbox"
        inside_sandbox(&block)
      end
    end
934054
def run (cmd, verbosity=0, **kwargs):
    """"""
    # Note that shell_quote_nt() result is not suitable for copy-paste
    # (especially on Unix systems), but it looks nicer than shell_quote().
    if verbosity >= 0:
        log_info("running %s" % " ".join(map(shell_quote_nt, cmd)))
    if kwargs:
        if verbosity >= 0:
            log_info("    with %s" % ", ".join("%s=%s" % (k, shell_quote(str(v)))\
                                           for k, v in kwargs.items()))
        if kwargs.get("shell"):
            # for shell calls the command must be a string
            cmd = " ".join(cmd)
    if verbosity < 1:
        # hide command output on stdout
        with open(os.devnull, 'wb') as devnull:
            kwargs['stdout'] = devnull
            res = subprocess.call(cmd, **kwargs)
    else:
        res = subprocess.call(cmd, **kwargs)
    return res
4030
def get_invoke(command):
    

    assert isinstance(command, click.Command)

    def invoke_(self, arg):  # pylint: disable=unused-argument
        try:
            command.main(args=shlex.split(arg),
                         prog_name=command.name,
                         standalone_mode=False,
                         parent=self.ctx)
        except click.ClickException as e:
            # Show the error message
            e.show()
        except click.Abort:
            # We got an EOF or Keyboard interrupt.  Just silence it
            pass
        except SystemExit:
            # Catch this an return the code instead. All of click's help commands do a sys.exit(),
            # and that's not ideal when running in a shell.
            pass
        except Exception as e:
            traceback.print_exception(type(e), e, None)
            logger.warning(traceback.format_exc())

        # Always return False so the shell doesn't exit
        return False

    invoke_ = update_wrapper(invoke_, command.callback)
    invoke_.__name__ = 'do_%s' % command.name
    return invoke_
1218593
def runshell(command)
      logger.info "+ #{command}"
      output = `#{command} < #{null_device} 2>&1`
      raise StandardError, "Command failure: #{output}" unless $?.success?
      output
    end
933900
def system_command(*command_args)
      cmd = Mixlib::ShellOut.new(*command_args)
      cmd.run_command
      cmd
    end
623795
def invoke(command, params={})
      command_string = compile_command(command, params)
      output_command(command_string)
      execute(command_string, params)
    end
1152143
def exec(*commands)
      ret = ''
      commands.each { |cmd| ret += shell.exec(cmd) }
      ret + shell.exec('exec')
    end
990629
function invoke() {
        parent::invoke();

        $result = true;

        // Set own core attributes
        $this->does_generate = ACTION_GENERATE_HTML;

        // These are always here
        global $CFG, $XMLDB, $OUTPUT;

        // Do the job, setting result as needed
        // Get the dir containing the file
        $dirpath = required_param('dir', PARAM_PATH);
        $dirpath = $CFG->dirroot . $dirpath;

        // Get the correct dirs
        if (!empty($XMLDB->dbdirs)) {
            $dbdir = $XMLDB->dbdirs[$dirpath];
        } else {
            return false;
        }
        if (!empty($XMLDB->editeddirs)) {
            $editeddir = $XMLDB->editeddirs[$dirpath];
            $structure = $editeddir->xml_file->getStructure();
        }

        $tables = $structure->getTables();
        $table = reset($tables);
        $defaulttable = null;
        if ($table) {
            $defaulttable = $table->getName();
        }

        // Get parameters
        $commandparam = optional_param('command', 'create_table', PARAM_PATH);
        $tableparam = optional_param('table', $defaulttable, PARAM_PATH);

        // The back to edit xml button
        $b = ' <p class="centerpara buttons">';
        $b .= '<a href="index.php?action=edit_xml_file&amp;dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '">[' . $this->str['back'] . ']</a>';
        $b .= '</p>';
        $o = $b;

        // Calculate the popup of commands
        $commands = array('create_table',
                         'drop_table',
                         'rename_table');
        foreach ($commands as $command) {
            $popcommands[$command] = str_replace('_', ' ', $command);
        }
        // Calculate the popup of tables
        foreach ($tables as $table) {
            $poptables[$table->getName()] = $table->getName();
        }
        // Now build the form
        $o.= '<form id="form" action="index.php" method="post">';
        $o.='<div>';
        $o.= '    <input type="hidden" name ="dir" value="' . str_replace($CFG->dirroot, '', $dirpath) . '" />';
        $o.= '    <input type="hidden" name ="action" value="view_structure_php" />';
        $o.= '    <table id="formelements" class="boxaligncenter" cellpadding="5">';
        $o.= '      <tr><td><label for="menucommand" accesskey="c">' . $this->str['selectaction'] .' </label>' . html_writer::select($popcommands, 'command', $commandparam, false) . '&nbsp;<label for="menutable" accesskey="t">' . $this->str['selecttable'] . ' </label>' .html_writer::select($poptables, 'table', $tableparam, false) . '</td></tr>';
        $o.= '      <tr><td colspan="2" align="center"><input type="submit" value="' .$this->str['view'] . '" /></td></tr>';
        $o.= '    </table>';
        $o.= '</div></form>';
        $o.= '    <table id="phpcode" class="boxaligncenter" cellpadding="5">';
        $o .= '      <tr><td><textarea cols="80" rows="32" class="form-control">';
        // Based on current params, call the needed function
        switch ($commandparam) {
            case 'create_table':
                $o.= s($this->create_table_php($structure, $tableparam));
                break;
            case 'drop_table':
                $o.= s($this->drop_table_php($structure, $tableparam));
                break;
            case 'rename_table':
                $o.= s($this->rename_table_php($structure, $tableparam));
                break;
        }
        $o.= '</textarea></td></tr>';
        $o.= '    </table>';

        $this->output = $o;

        // Launch postaction if exists (leave this here!)
        if ($this->getPostAction() && $result) {
            return $this->launch($this->getPostAction());
        }

        // Return ok if arrived here
        return $result;
    }