Perhaps you need something similar that what Expect does.
Check this code:
import pty
import os
my_list_accumulator = []
def read_stuff(fd):
output = os.read(fd, 1024)
my_list_accumulator.append(output)
return output
pty.spawn('python3', read_stuff)
Demo:
>>> import pty
>>> import os
>>>
>>> my_list_accumulator = []
>>>
>>> def read_stuff(fd):
... output = os.read(fd, 1024)
... my_list_accumulator.append(output)
... return output
...
...
>>> pty.spawn('python3', read_stuff)
Python 3.5.2 (default, Jul 17 2020, 14:04:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello', end='')
Hello>>> And this will give error
File "<stdin>", line 1
And this will give error
^
SyntaxError: invalid syntax
>>>
0
>>> # pressed Ctrl-D to escape
...
>>> print(b''.join(my_list_accumulator).decode('utf-8'))
Python 3.5.2 (default, Jul 17 2020, 14:04:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello', end='')
Hello>>> And this will give error
File "<stdin>", line 1
And this will give error
^
SyntaxError: invalid syntax
>>>
>>>
So, you can modify the read_stuff
function to do what you wish, but make sure to read the documentation: https://docs.python.org/3/library/pty.html