Sumit
Sumit

Reputation: 2023

python3.6 PEXPECT is not writing logs to a logfile

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)

Upvotes: 0

Views: 913

Answers (1)

shmee
shmee

Reputation: 5101

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>)

Upvotes: 1

Related Questions