我正在尝试将pexpect日志记录到文件中。该代码在python2.7中有效,但日志未在python3.6中打印
import pexpect
child = pexpect.spawn("telnet IP")
fout = open("abc.txt", "wb"):
child.logfile = fout
child.sendlines("somecommand)
答案 0 :(得分:1)
很难相信这段代码确实可以在Python 2.7中工作;)
child.logfile = fout
完成后,您的contextmanager会立即退出,因此,当您的子进程随后尝试对其进行写操作时,您的文件句柄将关闭。
您必须保持文件句柄打开,直到您的孩子完成操作,例如:
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>)