python3.6 PEXPECT is not writing logs to a logfile

混江龙づ霸主 提交于 2019-12-11 19:19:58

问题


I am trying to log pexpect logs to a file. The code was working in python2.7 but logs not getting printed in python3.6

import pexpect
child = pexpect.spawn("telnet IP")
fout = open("abc.txt", "wb"):
child.logfile = fout
child.sendlines("somecommand)

回答1:


It's a bit hard to believe that exactly this code was working in Python 2.7 ;)

Your contextmanager exits right after child.logfile = fout completes, hence your file handle is closed when your child process tries to write to it afterwards. You'll have to keep the file handle open until your child finishes, e.g.:

import pexpect
with open("abc.txt", "wb") as fout:
    child = pexpect.spawn("telnet IP")
    child.logfile = fout

# -- OR --

child = pexpect.spawn("telnet IP")
with open("abc.txt", "wb") as fout:
    child.logfile = fout
    child.expect(<some pattern here>)


来源:https://stackoverflow.com/questions/51721956/python3-6-pexpect-is-not-writing-logs-to-a-logfile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!