【问题标题】:TypeError when calling expect method of pexpect module in Python 3在 Python 3 中调用 pexpect 模块的 expect 方法时出现 TypeError
【发布时间】:2015-01-06 01:20:56
【问题描述】:

我正在尝试将 pexpect 模块(版本 3.3)与 Python 3.4.0 一起使用。我收到一个错误

TypeError: 必须是 str,而不是 bytes

当我调用 child.expect 方法时。

实际代码是来自 pexpect 文档的标准示例:

child = pexpect.spawn('ssh foo@bar.com')
index = child.expect([pexpect.TIMEOUT, pexpect.EOF, ssh_newkey, '.*password:'])

完全相同的代码可以在 pexpect 模块(3.1 版)和 Python 2.7.6 版中正常工作。

GitHub 上的 Pexpect 文档指出 pexpect 版本 3.3 需要 Python 2.6 或 3.2 或更高版本。尽管此模块的文档中有说明,但有人知道 pexpect 是否由于某种原因无法与 Python 3 一起使用?

这是我得到的回溯输出:

Traceback (most recent call last):
  File "/home/sambo9/python/python3-pexpect.py", line 17, in <module>
    main()
  File "/home/sambo9/python/python3-pexpect.py", line 13, in main
    child.expect('.*password:')
  File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 1451, in expect
    timeout, searchwindowsize)
  File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 1466, in expect_list
    timeout, searchwindowsize)
  File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 1535, in expect_loop
    c = self.read_nonblocking(self.maxread, timeout)
  File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 985, in read_nonblocking
    self._log(s, 'read')
  File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 908, in _log
    second_log.write(s)
  File "/usr/lib/python3.4/idlelib/PyShell.py", line 1339, in write
    raise TypeError('must be str, not ' + type(s).__name__)
TypeError: must be str, not bytes

此外,当我运行脚本时,我还看到通过 Ubuntu 上的 GUI 弹出“OpenSSH”框,提示输入密码。这在 Python 2.7.6 下不会发生。在 Python 2.7 中,我无需任何手动交互即可登录系统 - 一切都通过脚本自动发生。

【问题讨论】:

  • 回溯会很有帮助。
  • 可能与python3中的字符串/字节区分有关。如果有帮助,请参阅this 答案。
  • @ThiefMaster 这是调用expect方法后的回溯输出:

标签: python python-3.x pexpect


【解决方案1】:

来自documentation

# In Python 3, spawnu should be used to give str to stdout:
child = pexpect.spawnu('some_command')
child.logfile = sys.stdout

【讨论】:

  • 非常感谢布尔汉!使用“spawnu”类解决了我的问题。错误消息有些混乱 - 让我认为问题出在“expect”方法上。
  • 您可以在bug report 中了解更多关于该问题的信息,它还告诉我们,spawn 使用二进制日志文件,spawnu 使用 unicode 日志文件。
猜你喜欢
  • 1970-01-01
  • 2017-09-08
  • 2016-12-06
  • 2015-01-03
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
  • 2023-04-08
相关资源
最近更新 更多