【问题标题】:python3.6 PEXPECT is not writing logs to a logfilepython3.6 PEXPECT 没有将日志写入日志文件
【发布时间】:2018-08-07 08:13:45
【问题描述】:

我正在尝试将 pexpect 日志记录到文件中。该代码在 python2.7 中运行,但在 python3.6 中未打印日志

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

【问题讨论】:

  • “不工作”是什么意思?
  • 另外,您在对 shmee 的回答的评论中说,在移植到 3.6 时,您从问题的原始版本中添加了 with。但是with 破坏了代码。这就是你的问题的全部吗?
  • 这意味着我在日志文件中没有得到任何东西。还有一个 child.sendlines 命令我这里没有提到
  • 使用上面提到的代码,python3.6 中没有打印任何日志。

标签: python pexpect


【解决方案1】:

有点难以相信这段代码确实在 Python 2.7 中运行;)

您的上下文管理器在child.logfile = fout 完成后立即退出,因此当您的子进程随后尝试写入文件句柄时,您的文件句柄将关闭。 您必须保持文件句柄打开,直到您的孩子完成,例如:

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

【讨论】:

  • 你是对的。从 2.7 打印代码时出错。在 2.7 中,我没有使用 with 语句。我以 open("filename", "w") 的形式打开文件。我刚刚在堆栈溢出中编写此语句时修改了语句
猜你喜欢
  • 2018-03-21
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
  • 2021-04-26
  • 2012-10-06
相关资源
最近更新 更多