在Python 3中调用pexpect模块的expect方法时的TypeError

时间:2014-11-09 18:48:58

标签: python python-3.x pexpect

我正在尝试使用Python 3.4.0的pexpect模块(版本3.3)。我收到错误

  

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

此外,我还看到&#34; OpenSSH&#34;在我运行脚本时,在Ubuntu上通过GUI弹出框提示输入密码。这在Python 2.7.6下不会发生。在Python 2.7中,我可以在没有任何手动交互的情况下登录系统 - 一切都通过脚本自动发生。

1 个答案:

答案 0 :(得分:3)

来自documentation

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