![](/img/trans.png)
[英]Error decoding byte string in Python3 [TypeError: must be str, not bytes]
[英]expect in python3 is throwing error as “must be in str , not bytes”
我正在将我的代码迁移到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
pexpect
想记录字节,而不是解码字符串。 你可以让它做到这一点:
telconn.logfile = sys.stdout.buffer
sys.stdout
默认为期待字符串。 内部缓冲区很满意字节。
接受的答案是正确的,因为您当前正在尝试记录字节而不是字符串。 但至少从pexpect版本4.6开始,您可以为spawn
提供encoding
参数 。 所以使用:
telconn=pexpect.spawn('telnet 10.24.12.83', encoding='utf-8')
然后使用utf-8自动解码与生成的终端的所有通信,并且您将能够使用telconn.logfile = sys.stdout
。
在此错误报告中,您应该使用spawnu
而不是spawn
来编写unicode而不是字节。 您可能不知道spawn
使用二进制日志文件,而spawnu
使用unicode日志文件。
将第53行更改为
login1=telconn.expect(">"+"key to proceed.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.