I am migrating my code to python 3.4.3. This code works fine in python 2.4.3. but here it throws error in python 3.4.3. should I use anything different from expect ? Here is my code snippet which gets the error:
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(">")
The error what I get is :
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
wants to log bytes, not decoded strings. You can just let it do that:
telconn.logfile = sys.stdout.buffer
sys.stdout
defaults to expecting strings. Internal buffer is happy with bytes.
The accepted answer is correct in that you're currently trying to log bytes and not string. But at least as of pexpect version 4.6, you can provide the encoding
argument to spawn
. So use:
telconn=pexpect.spawn('telnet 10.24.12.83', encoding='utf-8')
Then all communication with the spawned terminal is automatically decoded using utf-8, and you'll be able to use telconn.logfile = sys.stdout
.
As of this bug report you should use spawnu
instead of spawn
to write unicode instead of bytes. You might not have known that spawn
uses binary logfiles, and spawnu
uses unicode logfiles.
将第53行更改为
login1=telconn.expect(">"+"key to proceed.")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.