Skip to content

Instantly share code, notes, and snippets.

Created Jan 27, 2022
What would you like to do?
Title: Attempting to use interact produces TypeError: write() argument must be str, not bytes
The following Python script using `pexpect` connects to the POP3
server ``. It does not download any email. It will
most likely work on any server.
# Connection variables: please include your own values
ip = ""
socket = "995"
user = xxxxxx
password = xxxxxx
import pexpect
import sys
cmd = f'openssl s_client -connect {ip}:{socket} -quiet'
child = pexpect.spawn(cmd, timeout=5, encoding='utf-8')
child.logfile_read = sys.stdout
child.sendline(f'user {user}')
child.sendline(f'pass {password}')
print("Exception was thrown")
print("debug information:")
Here is the output.
depth=2 C = US, O = DigiCert Inc, OU =, CN = DigiCert Global Root G2
verify return:1
depth=1 C = US, O = DigiCert Inc, OU =, CN = Thawte TLS RSA CA G1
verify return:1
depth=0 CN = *
verify return:1
+OK Dovecot ready.
user xxxxxxxxx
pass xxxxxxxxx
+OK Logged in.
+OK 9 messages:
1 134551
2 2599
3 2371
4 3341
5 2539
6 2541
7 2122
8 7185
9 7174
and I press any key, I get a bunch of diagnostic information from
`print(str(child))`, followed by the following traceback:
Traceback (most recent call last):
File "/tmp/pexpect.txt", line 31, in <module>
File "/usr/lib/python3/dist-packages/pexpect/", line 793, in interact
self.__interact_copy(escape_character, input_filter, output_filter)
File "/usr/lib/python3/dist-packages/pexpect/", line 838, in __interact_copy
self._log(data, 'read')
File "/usr/lib/python3/dist-packages/pexpect/", line 133, in _log
TypeError: write() argument must be str, not bytes
I thought the `encoding='utf-8'` argument to the `spawn` command was
supposed to take care of that issue.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment