【发布时间】: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