欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

對Python _取log的幾種方式小結(jié)

 更新時間:2019年07月25日 10:35:56   作者:Cengineering  
今天小編就為大家分享一篇對Python _取log的幾種方式小結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

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)#如果子進程結(jié)束了,你再去child.expect(pattern)會報EOF錯誤,模塊提供了一種方法,child.expect(pexpect.EOF),不會報錯,如果子進程結(jié)束了返回0
childlog.close()

2.改變標(biāo)準(zhǔn)輸出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 #備份當(dāng)前的標(biāo)準(zhǔn)輸出到命令行
childlog = open('promp.log',"w") #這里文件屬性不能為二進制,否則報錯TypeError: a bytes-like object is required, not 'str'
sys.stdout = childlog   #將childlog設(shè)為標(biāo)準(zhǔn)輸出的對像
child.expect(pexpect.EOF)
print(child.before.decode()) #這里使用decode()函數(shù),將輸出的目錄信息格式化
#child.before 這個值包含文本從頭一直到匹配的位置 
childlog.close()
sys.stdout = __console__  #還原標(biāo)準(zhǔn)輸出對象為命令行

以上這篇對Python _取log的幾種方式小結(jié)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論