wexpect - 一个可以自动化交互式shell输入的库

linux下有个pexpect的lib,可以实现一些交互式输入,pexpect网上的教程很多, 这里就不多说了;

但这个库不能用于windows,如果要实现windows下shell自动化交互式操作的话,可以参考python的wexpect

官方文档: https://wexpect.readthedocs.io/en/stable/index.html?highlight=wexpect

                https://pexpect.readthedocs.io/en/stable/overview.html#windows

安装

pip install wexpect

这个wexpect库对python版本有要求, 太旧的python版本无法安装,强行安装后也无法使用

Pexpect 需要 Python 3.3 或更高版本,或 Python 2.7,  那wexpect大概也是如此。

血的教训: 我第一次就强行装了wexpect,但是无法正常使用,就放弃了,但估计就是python版本问题,后来查阅资料,尝试安装activaTCL和expect.exe想用于交互式自动化,但要么就是网上的链接失效,要么就是找不到教程里的工具,再次放弃,这次重装了python,wexpect就可以正常使用了

简单使用

import wexpect
child = wexpect.spawn('c:\python38\python.exe')
ret = child.expect('>>>')
print("ret1",ret)
child.sendline('print(123456789)')
ret=child.expect('>>>')
print("ret2",ret)
print("++++++++++++++++",child.before,"---------------------")
print("******************",child.after,"******************")

child.sendline('print(987565)')
ret=child.expect('>>>')
print("ret3",ret)
print("++++++++++++++++",child.before,"---------------------")
print("******************",child.after,"******************")

child.sendline('a=100')
child.expect('>>>')
child.sendline('b=200')
child.expect('>>>')
child.sendline('print("a+b =",a+b)')
ret=child.expect('>>>')
print("ret4",ret)
print("++++++++++++++++",child.before,"---------------------")
print("******************",child.after,"******************")
child.sendline('exit()')
ret1 0
ret2 0
++++++++++++++++  print(123456789)
123456789
 ---------------------
****************** >>> ******************
ret3 0
++++++++++++++++  print(987565)
987565
 ---------------------
****************** >>> ******************
ret4 0
++++++++++++++++  print("a+b =",a+b)
a+b = 300
 ---------------------
****************** >>> ******************

unbelievable, 我打开了python交互式,并且交互式输入并计算其结果,读取返回值,这样一来就可以在我们pythonsv和csripts的自动化相关脚本里使用了.

subprocess也可以用于交互式,但是使用起来没有这个lib这么自由.

 

如果你安装wexpect失败,可以从这里下载我下载好的离线包去安装:

将下边四个文件下载放到同一个folder, 但你可能要改下文件拓展名

https://files.cnblogs.com/files/pfeiliu/requirement.txt.xml?t=1670083101

https://files.cnblogs.com/files/pfeiliu/pywin32-228-cp38-cp38-win_amd64.whl.xml?t=1670083059

https://files.cnblogs.com/files/pfeiliu/wexpect-4.0.0.tar.gz?t=1670082885

https://files.cnblogs.com/files/pfeiliu/psutil-5.9.4.tar.gz?t=1670082880

安装: C:\Python38\python.exe -m pip install --no-index --find-links=. -r requirement.txt
posted @ 2022-12-03 00:56  腹肌猿  阅读(633)  评论(0编辑  收藏  举报