对Python _取log的几种方式小结
作者:Cengineering 时间:2021-12-19 02:18:48
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__ #还原标准输出对象为命令行
来源:https://blog.csdn.net/Cengineering/article/details/79287786
标签:Python,log
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
移动测试开发Mitmproxy用于测试抓包神器详解
2023-08-30 23:34:55
![](https://img.aspxhome.com/file/2023/3/101003_0s.png)
零基础写python爬虫之爬虫编写全记录
2021-09-06 22:53:27
![](https://img.aspxhome.com/file/2023/0/97280_0s.jpg)
z-index在IE中的迷惑
2007-05-11 16:50:00
TensorFlow通过文件名/文件夹名获取标签,并加入队列的实现
2023-02-14 17:08:47
FrontPage XP设计教程3——网页的布局
2008-10-11 12:20:00
![](https://img.aspxhome.com/file/UploadPic/200810/17/20081017122538589s.jpg)
微信小程序picker组件简单用法示例
2023-07-23 10:49:32
![](https://img.aspxhome.com/file/2023/1/55921_0s.gif)
如何编写python的daemon程序
2023-07-27 05:13:28
儿童学习python的一些小技巧
2021-10-14 05:09:40
Django 外键的使用方法详解
2022-10-16 14:30:51
![](https://img.aspxhome.com/file/2023/0/90900_0s.png)
决策树的python实现方法
2023-04-22 04:25:02
python 三种方法提取pdf中的图片
2023-09-18 08:25:58
![](https://img.aspxhome.com/file/2023/1/95281_0s.jpg)
python3.6中anaconda安装sklearn踩坑实录
2023-03-16 19:17:15
![](https://img.aspxhome.com/file/2023/7/80407_0s.png)
python实现Windows电脑定时关机
2021-05-17 02:46:58
python控制台显示时钟的示例
2023-10-23 12:04:24
ASP自动清除ACCESS数据库的日文字符
2007-11-28 17:40:00
python计算n的阶乘的方法代码
2023-08-20 07:33:00
flask使用session保存登录状态及拦截未登录请求代码
2021-02-22 12:00:57
python matplotlib实现条形图的填充效果
2022-03-12 07:55:20
![](https://img.aspxhome.com/file/2023/1/79561_0s.jpg)
Python之修改图片像素值的方法
2022-03-14 03:46:18
pycharm必知的一些简单设置方法
2023-07-21 14:53:40
![](https://img.aspxhome.com/file/2023/7/61967_0s.png)