本文主要是介绍通过python控制命令行 subprocess,pexpect,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
通过python控制命令行
可选方案
- subprocess python原生,实在是难用
- pexpect 第三方,非常好用,但是demo复杂,完成简单功能还是可以的
pexpect
- 安装 pip install pexpect
- 代码来了哈
import pexpect
import reif __name__ == '__main__':username=password=keyword=child = pexpect.spawn('git clone https://gitee.com/superfun/rtl8021factory.git')ret = child.expect('Username') # 获取包含Username的返回,能捕获到if ret == 0:print(child.before, child.after)pattern = re.compile('Username') # 正则if re.match(pattern, child.after.decode()):child.sendline('superfun')ret = child.expect('Password') # 获取包含Username的返回,能捕获到if ret == 0:print(child.before, child.after)pattern = re.compile('Password') # 正则if re.match(pattern, child.after.decode()):child.sendline('hahahahahah')
补
后期碰到repo android source 需要无尽输入密码,我也是醉了,加了一个while循环,和timeout,让他自己去玩吧,不过仔细想想,还是哪里不对劲呢。不知道什么时候结束(这个不知道),超时时间太长了,如果错误也不知道(重复执行repo即可),感觉还是不够灵活。
这篇关于通过python控制命令行 subprocess,pexpect的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!