Python3中的pexpect.expect()抛出错误:"必须是字符串,而不是字节"。

13

我正在将我的代码迁移到Python 3.4.3。这段代码在Python 2.4.3中运行良好,但在这里在Python 3.4.3中会抛出错误。 我需要使用与以前不同的东西吗? 以下是导致错误的代码片段:

   telconn=pexpect.spawn('telnet 10.24.12.83')
    telconn.logfile = sys.stdout
    login=telconn.expect([":","key to proceed.",">"])
    if login==0:
        telconn.send("user1" + "\r")
        telconn.expect(":")
        telconn.send("paswd1" + "\r\r\r\r\n\n\n")
        login1=telconn.expect([">","key to proceed."])
        if login1==0:
            print("nothing")
        elif login1==1:
            telconn.expect("key to proceed.")
            telconn.send ("\003")
            telconn.expect(">")
    if login==1:
        telconn.send ("\003")
        telconn.expect(">")
        print("ctlc")
    elif login==2:
        telconn.send("\n\r")
        telconn.expect(">")

我收到的错误是:

Traceback (most recent call last):
  File "cleanup1.py", line 128, in <module>
    Connect()
  File "cleanup1.py", line 53, in Connect
    login=telconn.expect([":","key to proceed.",">"])
  File "/corp/global/install-dependent/python/3.4.3/lib/python3.4/site-packages/pexpect/spawnbase.py", line 315, in expect
    timeout, searchwindowsize, async)
  File "/corp/global/install-dependent/python/3.4.3/lib/python3.4/site-packages/pexpect/spawnbase.py", line 339, in expect_list
    return exp.expect_loop(timeout)
  File "/corp/global/install-dependent/python/3.4.3/lib/python3.4/site-packages/pexpect/expect.py", line 97, in expect_loop
    incoming = spawn.read_nonblocking(spawn.maxread, timeout)
  File "/corp/global/install-dependent/python/3.4.3/lib/python3.4/site-packages/pexpect/pty_spawn.py", line 455, in read_nonblocking
    return super(spawn, self).read_nonblocking(size)
  File "/corp/global/install-dependent/python/3.4.3/lib/python3.4/site-packages/pexpect/spawnbase.py", line 157, in read_nonblocking
    self._log(s, 'read')
  File "/corp/global/install-dependent/python/3.4.3/lib/python3.4/site-packages/pexpect/spawnbase.py", line 115, in _log
    self.logfile.write(s)
TypeError: must be str, not bytes
4个回答

26

pexpect 希望记录字节,而不是解码后的字符串。你可以直接让它这样做:

pexpect 希望记录字节,而不是解码后的字符串。你可以直接让它这样做:

telconn.logfile = sys.stdout.buffer

sys.stdout 默认期望字符串。内部缓冲区可以接受字节。


19

接受的答案是正确的,因为你目前正在尝试记录字节而不是字符串。但至少在pexpect版本4.6之后,你可以spawn提供encoding参数。所以使用:

telconn=pexpect.spawn('telnet 10.24.12.83', encoding='utf-8')

然后,使用 utf-8 自动解码与生成的终端的所有通信,您将能够使用 telconn.logfile = sys.stdout


这个答案比被接受的更好,因为在处理生成对象时不需要进一步更改。 - LCoelho
无论我在spawn中指定编码,出于某种原因,我仍然会收到错误。 - Don Charlie

4
根据这个错误报告,您应该使用spawnu而不是spawn来写入Unicode而不是字节。您可能不知道spawn使用二进制日志文件,而spawnu使用Unicode日志文件。

这个答案比被接受的答案更好,因为在处理生成对象时不需要进一步的更改。 - LCoelho
这个答案比@Kyle Barron的更好,因为重构更简单。 - LCoelho

0

将第53行更改为

login1=telconn.expect(">"+"key to proceed.")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接