问题
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