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") #文件屬性必須為二進(jìn)制寫+,否則會(huì)報(bào)錯(cuò) child.logfile = childlog child.expect(pexpect.EOF)#如果子進(jìn)程結(jié)束了,你再去child.expect(pattern)會(huì)報(bào)EOF錯(cuò)誤,模塊提供了一種方法,child.expect(pexpect.EOF),不會(huì)報(bào)錯(cuò),如果子進(jìn)程結(jié)束了返回0 childlog.close()
2.改變標(biāo)準(zhǔn)輸出sys.stdout的輸出對(duì)象,將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") #這里文件屬性不能為二進(jìn)制,否則報(bào)錯(cuò)TypeError: a bytes-like object is required, not 'str' sys.stdout = childlog #將childlog設(shè)為標(biāo)準(zhǔn)輸出的對(duì)像 child.expect(pexpect.EOF) print(child.before.decode()) #這里使用decode()函數(shù),將輸出的目錄信息格式化 #child.before 這個(gè)值包含文本從頭一直到匹配的位置 childlog.close() sys.stdout = __console__ #還原標(biāo)準(zhǔn)輸出對(duì)象為命令行
以上這篇對(duì)Python _取log的幾種方式小結(jié)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
