最近写一个自动化工具,需要多次进行人机交互,觉得python比较方便,示例如下。
- def run(self):
- try:
- child = pexpect.spawn('Your command')//要执行的命令或者脚本
- child.logfile = sys.stdout //
- child.expect('your pattern')//执行命令后需要匹配的结果
- child.sendline('some_command')/匹配成功后,发送命令
- while 1://执行上条命令,需要等待很久才会得到结果的,需要使用while否则报pexpect.TIMEOUT异常
- index = child.expect(['.* result file generated.*',pexpect.EOF, pexpect.TIMEOUT])
- if index == 0:
- break //匹配到项后,跳出循环
- elif index == 1:
- pass //continue to wait
- elif index == 2:
- pass //continue to wait
- child.sendline('exit')
- child.sendcontrol('c')
- child.interact()
- except OSError:
- sys.exit(0)
阅读(653) | 评论(0) | 转发(0) |