[Pexpect] TypeError: write() argument must be str, not bytes

it2024-12-12  17

目录

描述可能的原因

描述

在 pexpect 使用过程中, 当调用 interact() 时, 有以下报错:

Traceback (most recent call last): File "main.py", line 8, in <module> handler.interact() File "/Users/***/opt/anaconda3/envs/python38/lib/python3.8/site-packages/pexpect/pty_spawn.py", line 793, in interact self.__interact_copy(escape_character, input_filter, output_filter) File "/Users/***/opt/anaconda3/envs/python38/lib/python3.8/site-packages/pexpect/pty_spawn.py", line 853, in __interact_copy self._log(data, 'send') File "/Users/***/opt/anaconda3/envs/python38/lib/python3.8/site-packages/pexpect/spawnbase.py", line 129, in _log self.logfile.write(s) TypeError: write() argument must be str, not bytes

可能的原因

在调用 interact() 前设置了控制台日志输出, 如以下代码:

import sys import pexpect # 通过 logfile=sys.stdout 设置了控制台日志输出 handler = pexpect.spawn("ssh user@host", encoding='utf-8', logfile=sys.stdout) i = handler.expect(["password"]) if i == 0: handler.sendline("pwd") handler.interact()

因此, 在调用 interact() 之前, 要确保控制台日志输出为空, 如以下代码:

import sys import pexpect # 通过 logfile=sys.stdout 设置了控制台输出 handler = pexpect.spawn("ssh user@host", encoding='utf-8', logfile=sys.stdout) i = handler.expect(["password"]) if i == 0: handler.sendline("pwd") # 控制台日志输出设置为空 handler.logfile = None handler.interact()
最新回复(0)