Skip to content
Advertisement

pexpect.expect() in python3 is throwing error as “must be in str , not bytes”

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" + "rrrrnnn")
        login1=telconn.expect([">","key to proceed."])
        if login1==0:
            print("nothing")
        elif login1==1:
            telconn.expect("key to proceed.")
            telconn.send ("03")
            telconn.expect(">")
    if login==1:
        telconn.send ("03")
        telconn.expect(">")
        print("ctlc")
    elif login==2:
        telconn.send("nr")
        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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement