首页 > 编程 > Python > 正文

对Python _取log的几种方式小结

2019-11-25 12:14:01
字体:
来源:转载
供稿:网友

1. 使用.logfile 方法

#!/usr/bin/env pythonimport pexpectimport syshost="146.11.85.xxx"user="inteuser"password="xxxx"command="ls -l"child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))child.expect('password:')child.sendline(password)childlog = open('promp.log',"ab") #文件属性必须为二进制写+,否则会报错child.logfile = childlogchild.expect(pexpect.EOF)#如果子进程结束了,你再去child.expect(pattern)会报EOF错误,模块提供了一种方法,child.expect(pexpect.EOF),不会报错,如果子进程结束了返回0childlog.close()

2.改变标准输出sys.stdout的输出对象,将log print到文件

#!/usr/bin/env pythonimport pexpectimport syshost="146.11.85.xxx"user="inteuser"password="xxxx"command="ls -l"child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))child.expect('password:')child.sendline(password)__console__ = sys.stdout #备份当前的标准输出到命令行childlog = open('promp.log',"w") #这里文件属性不能为二进制,否则报错TypeError: a bytes-like object is required, not 'str'sys.stdout = childlog   #将childlog设为标准输出的对像child.expect(pexpect.EOF)print(child.before.decode()) #这里使用decode()函数,将输出的目录信息格式化#child.before 这个值包含文本从头一直到匹配的位置 childlog.close()sys.stdout = __console__  #还原标准输出对象为命令行

以上这篇对Python _取log的几种方式小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表