Puts the connection into ASCII (text) mode, issues the given command, and
 passes the resulting data, one line at a time, to the associated block. If
 no block is given, prints the lines. Note that +cmd+ is a server command
 (such as "RETR myfile").
162501
def retrlines(cmd) # :yield: line
      synchronize do
	with_binary(false) do
          conn = transfercmd(cmd)
          loop do
            line = conn.gets
            break if line == nil
            if line[-2, 2] == CRLF
              line = line[0 .. -3]
            elsif line[-1] == ?\n
              line = line[0 .. -2]
            end
            yield(line)
          end
          conn.close
          voidresp
        end
      end
    end
415196
def print_commands():
    
    dummy_log_file = Log()
    commands = Log.commands()
    commands.sort()

    for cmd in commands:
        cmd = getattr(dummy_log_file, 'cmd_{0}'.format(cmd))
        description = cmd.__doc__
        if description:
            description = re.sub(r'\n\s+', ' ', description)
            description = description.strip()

        print('{0}: {1}\n'.format(cmd.__name__, description))
42638
def cmd(name, *params)
      @mutex.synchronize do
        connect unless connected?
        @conn.write "#{name} #{params.join(' ').gsub('\\', '\\\\\\')}\n"
        status, length = conn_gets.split # <status> <content_length>\n
        content = conn_read(length.to_i + 1) # +1 = \n
        content.chomp!
        raise CommandFailed, "Command #{name} returned with status #{status}: #{content}" if status.to_i != 200
        content
      end
    end
1316597
def retrlines(cmd) # :yield: line
      synchronize do
	voidcmd("TYPE A")
	conn = transfercmd(cmd)
	loop do
	  line = conn.gets
	  break if line == nil
	  if line[-2, 2] == CRLF
	    line = line[0 .. -3]
	  elsif line[-1] == ?\n
	    line = line[0 .. -2]
	  end
	  yield(line)
	end
	conn.close
	voidresp
      end
    end
1239618
def _do_print(self, cmd, args):
        
        name = args[0].strip()
        if not name:
            self.stderr.write('TODO: Display names of inspectable objects.\n')
            return
        try:
            code = textwrap.dedent(r'''
                    self.stdout.write(name + ':\n' + textwrap.indent(pprint.pformat({}), '    ') + '\n')
                    ''').format(name).strip()
            eval(code, globals(), locals())
        except NameError:
            self.stderr.write("p: name '{}' is not defined\n".format(name))
        self.stdout.flush()
471932
def cmd_as_file(cmd, *args, **kwargs):
    """"""
    kwargs['stdout'] = subprocess.PIPE
    stdin = kwargs.pop('stdin', None)
    if isinstance(stdin, basestring):
        with tempfile.TemporaryFile() as stdin_file:
            stdin_file.write(stdin)
            stdin_file.seek(0)
            kwargs['stdin'] = stdin_file
            p = subprocess.Popen(cmd, *args, **kwargs)
    else:
        p = subprocess.Popen(cmd, *args, **kwargs)
    try:
        yield p.stdout
    finally:
        p.stdout.close()
        if p.wait():
            raise subprocess.CalledProcessError(p.returncode, cmd)
1144645
protected final void printCommandLine(@Nonnull String[] cmd, @CheckForNull FilePath workDir) {
        StringBuilder buf = new StringBuilder();
        if (workDir != null) {
            buf.append('[');
            if(showFullPath)
                buf.append(workDir.getRemote());
            else
                buf.append(workDir.getRemote().replaceFirst("^.+[/\\\\]", ""));
            buf.append("] ");
        }
        buf.append('$');
        for (String c : cmd) {
            buf.append(' ');
            if(c.indexOf(' ')>=0) {
                if(c.indexOf('"')>=0)
                    buf.append('\'').append(c).append('\'');
                else
                    buf.append('"').append(c).append('"');
            } else
                buf.append(c);
        }
        listener.getLogger().println(buf.toString());
        listener.getLogger().flush();
    }
1142590
def _run_cmd_get_output(cmd):
    
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    out, err = process.communicate()
    return out or err
677616
def add_command(command=nil,&block)
      command = Commands::Command.new(&block) if block_given?
      current_connection.add_command(command)
    end
297485
def sendline(command):
    '''
    
    '''
    if ping() is False:
        init()
    out, _ = DETAILS[_worker_name()].sendline(command)
    return out
148034
async def send_cmd(self, cmd, loop=None):
        """"""
        _LOGGER.info("Send cmd = %s", cmd)

        if cmd not in COMMANDS and cmd not in range(0, 999):
            _LOGGER.error("Unknown command")
            raise PyMediaroomError("Unknown commands")

        keys = []
        if cmd in range(0, 999):
            for character in str(cmd):
                keys.append(COMMANDS["Number"+str(character)])
            if len(keys) < 3:
                keys.append(COMMANDS["OK"])
            self.current_channel = cmd
        else:
            keys = [COMMANDS[cmd]]

        try:
            async with timeout(OPEN_CONTROL_TIMEOUT, loop=loop):
                async with self.lock:
                    _LOGGER.debug("Connecting to %s:%s", self.stb_ip, REMOTE_CONTROL_PORT)
                    stb_recv, stb_send = await asyncio.open_connection(self.stb_ip,
                                                                       REMOTE_CONTROL_PORT,
                                                                       loop=loop)
                    await stb_recv.read(6)
                    _LOGGER.info("Connected to %s:%s", self.stb_ip, REMOTE_CONTROL_PORT)

                    for key in keys:
                        _LOGGER.debug("%s key=%s", cmd, key)
                        stb_send.write("key={}\n".format(key).encode('UTF-8'))
                        _ = await stb_recv.read(3)
                        await asyncio.sleep(0.300)

        except asyncio.TimeoutError as error:
            _LOGGER.warning(error)
            raise PyMediaroomError("Timeout connecting to {}".format(self.stb_ip))
        except ConnectionRefusedError as error:
            _LOGGER.warning(error)
            raise PyMediaroomError("Connection refused to {}".format(self.stb_ip))
1197289
def do_cmd(self, line):
        ''''''
        try:
            args = self.cmd_parser.parse_args(line.split())
        except ValueError as err:
            return error(err)

        # Check if args.service is valid
        if args.service not in SUPPORTED_SERVICES:
            return error('No Service: ' + args.service)

        args.params = ''.join(args.params)
        # params is optional
        if not args.params.strip():
            args.params = '{}'

        # params must be a dictionary format string
        match = re.match(r"^.*?(\{.*\}).*$", args.params)
        if not match:
            return error('Invalid params')

        try:
            args.params = dict(literal_eval(match.group(1)))
        except ValueError as err:
            return error('Invalid params')

        try:
            # Get ONVIF service
            service = self.client.get_service(args.service)
            # Actually execute the command and get the response
            response = getattr(service, args.operation)(args.params)
        except MethodNotFound as err:
            return error('No Operation: %s' % args.operation)
        except Exception as err:
            return error(err)

        if isinstance(response, (Text, bool)):
            return success(response)
        # Try to convert instance to dictionary
        try:
            success(ONVIFService.to_dict(response))
        except ONVIFError:
            error({})
73114
def executeCommand(self, command):
        
        if not command.strip():
            return self.waitForInput()
        
        # store the current block
        self._history.append(command)
        self._currentHistoryIndex = len(self._history)
        
        lines = []
        for line in command.split('\n'):
            line = re.sub('^>>> ', '', line)
            line = re.sub('^\.\.\. ', '', line)
            lines.append(line)
        
        command = '\n'.join(lines)
        
        # ensure we are at the end
        self.moveCursor(QTextCursor.End)
        self.scrollToEnd()
        self.insertPlainText('\n')
        cmdresult = None
        
        try:
            cmdresult = eval(command, self.scope(), self.scope())
        
        except SyntaxError:
            exec(command) in self.scope(), self.scope()
        
        else:
            if cmdresult is not None:
                # check to see if the command we executed actually caused
                # the destruction of this object -- if it did, then
                # the commands below will error
                if self.isDestroyed():
                    return
                
                try:
                    result = projex.text.nativestring(repr(cmdresult))
                except:
                    result = '<<< error formatting result to utf-8 >>>'
                
                self.information(result)
        
        finally:
            self.waitForInput()
951059
def print_help(self, file=None):
        
        output = file or self.stderr
        CustomStderrOptionParser.print_help(self, output)
        output.write("\nCommands:\n")
        for command_def in self.command_definitions.values():
            command_def.opt_parser.print_help(output)
            output.write("\n")
1106794
def retrlines(cmd) # :yield: line
      synchronize do
        with_binary(false) do
          begin
            conn = transfercmd(cmd)
            loop do
              line = conn.gets
              break if line == nil
              yield(line.sub(/\r?\n\z/, ""), !line.match(/\n\z/).nil?)
            end
            conn.shutdown(Socket::SHUT_WR)
            conn.read_timeout = 1
            conn.read
          ensure
            conn.close if conn
          end
          voidresp
        end
      end
    end
352675
def _read_output(self, command):
        
        cmd = []
        cmd.extend(self._prefix)
        cmd.extend([self._path, "-iP"])
        cmd.extend(command)
        command = cmd

        logger.debug("Cmd %s" % command)
        null = open('/dev/null', 'w')
        process = subprocess.Popen(
            command, stdout=subprocess.PIPE, stderr=null)
        null.close()

        results = []
        reader = csv.reader(_input_csv(process.stdout), delimiter=str("|"))

        try:
            headers = next(reader)
            logger.debug("<-- headers %s" % headers)
        except StopIteration:
            logger.debug("Cmd %s headers not found" % command)
            headers = []

        for row in reader:
            _output_csv(row)

            logger.debug("<-- row %s" % row)
            this_row = {}

            i = 0
            for i in range(0, len(headers)):
                key = headers[i]
                value = row[i]
                this_row[key] = value

            results.append(this_row)

        process.stdout.close()
        retcode = process.wait()
        if retcode != 0:
            logger.error("<-- Cmd %s returned %d (error)" % (command, retcode))
            raise subprocess.CalledProcessError(retcode, command)

        if len(headers) == 0:
            logger.error("Cmd %s didn't return any headers." % command)
            raise RuntimeError("Cmd %s didn't return any headers." % command)

        logger.debug("<-- Returned: %d (good)" % retcode)
        return results
597798
async def issue_cmd(self, cmd, value, retry=3):
        
        async with self._cmd_lock:
            if not self.connected:
                _LOGGER.debug(
                    "Serial transport closed, not sending command %s", cmd)
                return
            while not self._cmdq.empty():
                _LOGGER.debug("Clearing leftover message from command queue:"
                              " %s", await self._cmdq.get())
            _LOGGER.debug("Sending command: %s with value %s", cmd, value)
            self.transport.write(
                '{}={}\r\n'.format(cmd, value).encode('ascii'))
            if cmd == OTGW_CMD_REPORT:
                expect = r'^{}:\s*([A-Z]{{2}}|{}=[^$]+)$'.format(cmd, value)
            else:
                expect = r'^{}:\s*([^$]+)$'.format(cmd)

            async def send_again(err):
                """Resend the command."""
                nonlocal retry
                _LOGGER.warning("Command %s failed with %s, retrying...", cmd,
                                err)
                retry -= 1
                self.transport.write(
                    '{}={}\r\n'.format(cmd, value).encode('ascii'))

            async def process(msg):
                """Process a possible response."""
                _LOGGER.debug("Got possible response for command %s: %s", cmd,
                              msg)
                if msg in OTGW_ERRS:
                    # Some errors appear by themselves on one line.
                    if retry == 0:
                        raise OTGW_ERRS[msg]
                    await send_again(msg)
                    return
                if cmd == OTGW_CMD_MODE and value == 'R':
                    # Device was reset, msg contains build info
                    while not re.match(
                            r'OpenTherm Gateway \d+\.\d+\.\d+', msg):
                        msg = await self._cmdq.get()
                    return True
                match = re.match(expect, msg)
                if match:
                    if match.group(1) in OTGW_ERRS:
                        # Some errors are considered a response.
                        if retry == 0:
                            raise OTGW_ERRS[match.group(1)]
                        await send_again(msg)
                        return
                    ret = match.group(1)
                    if cmd == OTGW_CMD_SUMMARY and ret == '1':
                        # Expects a second line
                        part2 = await self._cmdq.get()
                        ret = [ret, part2]
                    return ret
                if re.match(r'Error 0[1-4]', msg):
                    _LOGGER.warning("Received %s. If this happens during a "
                                    "reset of the gateway it can be safely "
                                    "ignored.", msg)
                    return
                _LOGGER.warning("Unknown message in command queue: %s", msg)
                await send_again(msg)

            while True:
                msg = await self._cmdq.get()
                ret = await process(msg)
                if ret is not None:
                    return ret