对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编程使用tkinter模块实现计算器软件完整代码示例

Python编程使用tkinter模块实现计算器软件完整代码示例

Python 提供了多个图形开发界面的库。Tkinter就是其中之一。 Tkinter 模块(Tk 接口)是 Python 的标准 Tk GUI 工具包的接口 .Tk 和 Tkinter...

python实现画圆功能

python实现画圆功能

本文实例为大家分享了python实现画圆功能的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- """ __author__= 'Du' __...

python回调函数的使用方法

有两种类型的回调函数:复制代码 代码如下:blocking callbacks (also known as synchronous callbacks or just callback...

python3安装speech语音模块的方法

python3安装speech语音模块的方法

在windows平台上使用pyhton编写语音识别程序需要用到speech模块,speech模块支持的主要功能有:文本合成语音,将键盘输入的文本信息转换为语音信号方式输出;语音识别,将输...

实例详解python函数的对象、函数嵌套、名称空间和作用域

函数的对象 python中一切皆对象 函数对象的四大功能 引用 def f1(): print('from f1') f1() #调用函数 print(f1) print('*'...