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

yipeiwu_com6年前Python基础

1. 使用.logfile 方法

#!/usr/bin/env python
import pexpect
import sys
host="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 = childlog
child.expect(pexpect.EOF)#如果子进程结束了,你再去child.expect(pattern)会报EOF错误,模块提供了一种方法,child.expect(pexpect.EOF),不会报错,如果子进程结束了返回0
childlog.close()

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

#!/usr/bin/env python
import pexpect
import sys
host="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的几种方式小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现统计文本文件字数的方法

本文实例讲述了Python实现统计文本文件字数的方法。分享给大家供大家参考,具体如下: 统计文本文件的字数,从当前目录下的file.txt取文件 # -*- coding: GBK...

Python下的twisted框架入门指引

什么是twisted? twisted是一个用python语言写的事件驱动的网络框架,他支持很多种协议,包括UDP,TCP,TLS和其他应用层协议,比如HTTP,SMTP,NNTM,IR...

Python中unittest模块做UT(单元测试)使用实例

待测试的类(Widget.py) # Widget.py # Python 2.7.6 class Widget: def __init__(self, size =...

Python之用户输入的实例

Python之用户输入的实例

大多数程序都旨在解决最终用户的问题,为此,需要从用户那里获取一些信息。函数input()让程序暂停运行,等待用户输入一些文本。 例如: name = input("Please in...

python实现比对美团接口返回数据和本地mongo数据是否一致示例

本文实例讲述了python实现比对美团接口返回数据和本地mongo数据是否一致。分享给大家供大家参考,具体如下: 应用背景:美团平台商品的上下架状态、库存、售价,和mongo库存储的是否...