当前位置: 首页>>代码示例>>Python>>正文


Python Expect.expect方法代码示例

本文整理汇总了Python中expect.Expect.expect方法的典型用法代码示例。如果您正苦于以下问题:Python Expect.expect方法的具体用法?Python Expect.expect怎么用?Python Expect.expect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在expect.Expect的用法示例。


在下文中一共展示了Expect.expect方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: RRInstance

# 需要导入模块: from expect import Expect [as 别名]
# 或者: from expect.Expect import expect [as 别名]
class RRInstance(object):
    def __init__(self, description, rr_replay, source_pane):
        self.rr_replay = rr_replay
        self.description = description
        self.spawn_cmd = "{} replay {}".format(
            shlex.quote(cli_args.rr), shlex.quote(rr_replay))
        self.source_pane = source_pane

        self.breakpoints = {}
        self.watches_set = 0
        self.instr_to_checkpoint = sorteddict()

    def __repr__(self):
        return "RRInstance({!r})".format(self.description)

    @cached_property
    def arch(self):
        rr_ps = check_output([cli_args.rr, 'ps', self.rr_replay])
        qemu_regex = r"qemu-system-({})".format("|".join(SUPPORTED_ARCHS.keys()))
        re_result = re.search(qemu_regex, rr_ps)
        if not re_result: raise RuntimeError("Unsupported architecture!")
        return SUPPORTED_ARCHS[re_result.group(1)]

    # Runs in child process.
    def sendline(self, msg):
        check_call(['tmux', 'send-keys', '-t', self.pane, '-l', msg])
        check_call(['tmux', 'send-keys', '-t', self.pane, 'ENTER'])

    # Runs in child process.
    def kill(self):
        check_call(['tmux', 'kill-pane', '-t', self.pane])

    def __enter__(self):
        self.tempdir_obj = TempDir()
        tempdir = self.tempdir_obj.__enter__()
        logfile = join(tempdir, self.description + "out")
        os.mkfifo(logfile)
        bash_command = "{} 2>&1 | tee -i --output-error=warn {} | tee -i --output-error=warn {}_log.txt".format(
            self.spawn_cmd, shlex.quote(logfile), self.description)

        self.pane = check_output([
            'tmux', 'split-window', '-hdP',
            '-F', '#{pane_id}', '-t', pane,
            'bash', '-c', bash_command]).strip()

        self.proc = Expect(os.open(logfile, os.O_RDONLY | os.O_NONBLOCK), quiet=True)
        try:
            self.proc.expect("(rr) ", timeout=3)
        except TimeoutExpired:
            print(self.proc.sofar)
            raise
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            self.kill()
        self.tempdir_obj.__exit__(exc_type, exc_value, traceback)

    def gdb(self, *args, **kwargs):
        timeout = kwargs.get('timeout', None)
        cmd = " ".join(map(str, args))
        print("(rr-{}) {}".format(self.description, cmd))
        sys.stdout.flush()

        expect_prompt = kwargs.get("expect_prompt", "(rr) ")

        while True:
            try:
                os.read(self.proc.fd, 1024)
            except OSError as e:
                if e.errno in [EAGAIN, EWOULDBLOCK]: break
                else: raise
        self.sendline(cmd)

        try:
            output = self.proc.expect(expect_prompt, timeout=timeout)
        except TimeoutExpired:
            print(self.proc.sofar)
            print("EXCEPTION!")
            sys.stdout.flush()

        if output.endswith(expect_prompt): output = output[:-len(expect_prompt)]
        if output.startswith(cmd): output = output[len(cmd):]
        return output.strip()

    def quit(self):
        self.gdb("set confirm off")
        self.sendline("quit")

    def gdb_int_re(self, result_re, *args):
        result = self.gdb(*args)
        return re_search_int(result_re, result)

    def breakpoint(self, break_arg):
        bp_num = self.gdb_int_re(r"Breakpoint ([0-9]+) at", "break", break_arg)
        self.breakpoints[break_arg] = bp_num

    def disable_all(self):
        self.gdb("disable")
        self.watches_set = 0
#.........这里部分代码省略.........
开发者ID:m000,项目名称:panda,代码行数:103,代码来源:diverge.py

示例2: Qemu

# 需要导入模块: from expect import Expect [as 别名]
# 或者: from expect.Expect import expect [as 别名]
class Qemu(object):
    def __init__(self, qemu_path, qcow, snapshot, tempdir, boot=False, rr=False):
        self.qemu_path = qemu_path
        self.qcow = qcow
        self.snapshot = snapshot
        self.tempdir = tempdir
        self.rr = rr
        self.boot = boot

    # types a command into the qemu monitor and waits for it to complete
    def run_monitor(self, cmd):
        if debug:
            print "monitor cmd: [%s]" % cmd
        print Style.BRIGHT + "(qemu)" + Style.RESET_ALL,
        self.monitor.sendline(cmd)
        self.monitor.expect("(qemu)")
        print
        print

    def type_console(self, cmd):
        assert (not self.boot)
        if debug:
            print "console cmd: [%s]" % cmd
        self.console.send(cmd)

    # types a command into the guest os and waits for it to complete
    def run_console(self, cmd=None, timeout=30, expectation="[email protected]:~#"):
        assert (not self.boot)
        if cmd is not None:
            self.type_console(cmd)
        print Style.BRIGHT + "[email protected]:~#" + Style.RESET_ALL,
        self.console.sendline()
        self.console.expect(expectation, timeout=timeout)
        print
        print

    def __enter__(self):
        monitor_path = join(self.tempdir, 'monitor')
        if not self.boot:
            serial_path = join(self.tempdir, 'serial')

        qemu_args = [self.qemu_path, self.qcow]
#        if not self.boot:
#        
        qemu_args.extend(['-monitor', 'unix:{},server,nowait'.format(monitor_path)])
        if self.boot:
            qemu_args.append('-S')
        else:
            qemu_args.extend(['-serial', 'unix:{},server,nowait'.format(serial_path),
                              '-loadvm', self.snapshot])
        qemu_args.extend(['-display', 'none'])
        if self.rr: qemu_args = ['rr', 'record'] + qemu_args

        progress("Running qemu with args:")
        print subprocess32.list2cmdline(qemu_args)

        DEVNULL = open(os.devnull, "w")
        self.qemu = subprocess32.Popen(qemu_args) # , stdout=DEVNULL, stderr=DEVNULL)
        while not os.path.exists(monitor_path):
            time.sleep(0.1)
        if not self.boot:
            while not os.path.exists(serial_path):
                time.sleep(0.1)
#        while not all([os.path.exists(p) for p in [monitor_path, serial_path]]):
#            time.sleep(0.1)

        self.monitor_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.monitor_socket.connect(monitor_path)
        self.monitor = Expect(self.monitor_socket)
        if not self.boot:
            self.serial_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.serial_socket.connect(serial_path)
            self.console = Expect(self.serial_socket)

        # Make sure monitor/console are in right state.
        self.monitor.expect("(qemu)")
        print
        if not self.boot:
            self.console.sendline()
            self.console.expect("[email protected]:~#")
        print
        print

        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if traceback:
            print_exception(exc_type, exc_value, traceback)
        else:
            self.monitor.sendline("quit")
            self.monitor_socket.close()
            if not self.boot:
                self.serial_socket.close()

        try:
            self.qemu.wait(timeout=3)
        except subprocess32.TimeoutExpired:
            progress("Qemu stailed. Sending SIGTERM...")
            self.qemu.terminate()

#.........这里部分代码省略.........
开发者ID:mewbak,项目名称:panda,代码行数:103,代码来源:run_guest.py

示例3: RRInstance

# 需要导入模块: from expect import Expect [as 别名]
# 或者: from expect.Expect import expect [as 别名]
class RRInstance(object):
    def __init__(self, description, rr_replay, source_pane):
        self.description = description
        self.spawn_cmd = "{} replay {}".format(
            pipes.quote(cli_args.rr), pipes.quote(rr_replay))
        self.source_pane = source_pane

        self.breakpoints = {}
        self.watches_set = 0

    def __repr__(self):
        return "RRInstance({!r})".format(self.description)

    # Runs in child process.
    def sendline(self, msg):
        check_call(['tmux', 'send-keys', '-t', self.pane, '-l', msg])
        check_call(['tmux', 'send-keys', '-t', self.pane, 'ENTER'])

    # Runs in child process.
    def kill(self):
        check_call(['tmux', 'kill-pane', '-t', self.pane])

    def __enter__(self):
        self.tempdir_obj = TempDir()
        tempdir = self.tempdir_obj.__enter__()
        logfile = join(tempdir, self.description + "out")
        os.mkfifo(logfile)
        bash_command = "{} 2>&1 | tee -i --output-error=warn {} | tee -i --output-error=warn {}_log.txt".format(
            self.spawn_cmd, pipes.quote(logfile), self.description)

        self.pane = check_output([
            'tmux', 'split-window', '-hdP',
            '-F', '#{pane_id}', '-t', pane,
            'bash', '-c', bash_command]).strip()

        self.proc = Expect(os.open(logfile, os.O_RDONLY | os.O_NONBLOCK), quiet=True)
        self.proc.expect("(rr) ")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            self.kill()
        self.tempdir_obj.__exit__(exc_type, exc_value, traceback)

    def gdb(self, *args, **kwargs):
        timeout = kwargs.get('timeout', None)
        cmd = " ".join(map(str, args))
        print "(rr-{}) {}".format(self.description, cmd)
        sys.stdout.flush()

        while True:
            try:
                os.read(self.proc.fd, 1024)
            except OSError as e:
                if e.errno in [EAGAIN, EWOULDBLOCK]:
                    break
                else:
                    raise
        self.sendline(cmd)

        try:
            output = self.proc.expect("(rr) ", timeout=timeout)
        except TimeoutExpired:
            print self.proc.sofar
            print "EXCEPTION!"
            sys.stdout.flush()

        return output

    def quit(self):
        self.gdb("set confirm off")
        self.sendline("quit")

    def breakpoint(self, break_arg):
        result = self.gdb("break", break_arg)
        bp_num = int(re.search(r"Breakpoint ([0-9]+) at", result).group(1))
        self.breakpoints[break_arg] = bp_num

    def disable_all(self):
        self.gdb("disable")

    def enable(self, break_arg):
        self.gdb("enable", self.breakpoints[break_arg])

    def condition(self, break_arg, cond):
        self.gdb("condition", self.breakpoints[break_arg], cond)

    def condition_instr(self, break_arg, op, instr):
        if not hasattr(self, 'instr_count_ptr'):
            self.instr_count_ptr = self.get_value(
                "&cpus->tqh_first->rr_guest_instr_count")
        self.condition(
            break_arg, "*(uint64_t *){} {} {}".format(self.instr_count_ptr, op, instr))

    def get_value(self, value_str):
        result = self.gdb("print/u", value_str)
        re_result = re.search(r"\$[0-9]+ = ([0-9]+)", result)
        if re_result:
            return long(re_result.group(1))
        else:
#.........这里部分代码省略.........
开发者ID:mewbak,项目名称:panda,代码行数:103,代码来源:diverge.py


注:本文中的expect.Expect.expect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。