python中Pexpect的工作流程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1、工作流程步骤

(1)用spawn来执行一个程序;

(2)用expect方法来等待指定的关键字,这个关键字是被执行的程序打印到标准输出上面的;

(3)当发现这个关键字以后,使用send/sendline方法发送字符串给这个程序。

2、实例

spawn类

classspawn(SpawnBase):
'''ThisisthemainclassinterfaceforPexpect.Usethisclasstostart
andcontrolchildapplications.'''

#Thisispurelyinformationalnow-changingithasnoeffect
use_native_pty_fork=use_native_pty_fork

def__init__(self,command,args=[],timeout=30,maxread=2000,
searchwindowsize=None,logfile=None,cwd=None,env=None,
ignore_sighup=False,echo=True,preexec_fn=None,
encoding=None,codec_errors='strict',dimensions=None,
use_poll=False):

通过spawn()方法用来执行一个程序,返回程序的操作句柄,后续就可以通过操作句柄来与这个程序进行交互了。