簡體   English   中英

期望在python3中拋出錯誤為“必須在str中,而不是字節”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM