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

yipeiwu_com5年前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读取TXT每行,并存到LIST中的方法

python读取TXT每行,并存到LIST中的方法

文本如图: Python: import sys result=[] with open('accounts.txt','r') as f: for line in f: re...

python3中rank函数的用法

网上存在这么一个例子 obj = pd.Series([7,-5,7,4,2,0,4]) obj.rank() 输出为: 0 6.5 1 1.0 2 6.5 3 4....

pytorch 实现tensor与numpy数组转换

看代码,tensor转numpy: a = torch.ones(2,2) b = a.numpy() c=np.array(a) #也可以转numpy数组 print(type(a...

如何基于Python批量下载音乐

如何基于Python批量下载音乐

这篇文章主要介绍了如何基于Python批量下载音乐,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 音乐是生活的调剂品,目前很多的音乐只...

快速解决pandas.read_csv()乱码的问题

pandas.read_csv()遇到读进来乱码问题 1.设置encoding='gbk'或者encoding='utf-8'。pandas.read_csv('data.csv',en...