Skip to content

Instantly share code, notes, and snippets.

@luistung
Created February 22, 2025 15:15
Show Gist options
  • Save luistung/ba21348b637d1833bdd4c57906a8a911 to your computer and use it in GitHub Desktop.
Save luistung/ba21348b637d1833bdd4c57906a8a911 to your computer and use it in GitHub Desktop.
how to control with other interactive applications
import pexpect
import re
def interact_with_repl():
child = pexpect.spawn('python3')
child.expect(['>>> '])
expect_ret = '>>> '
while True:
command = input(expect_ret)
if command.lower() == 'exit':
child.sendline('exit()')
break
command = command.replace('\t', ' ')
#print('['+command+']')
child.sendline(command)
except_list = ['>>> ',
'... '
]
expect_ret = except_list[child.expect(list(map(re.escape, except_list)))]
before = child.before.decode('utf-8')
#print('{'+repr(before)+'}')
print(before[len(command+'\r\n'):], end='')
child.close()
interact_with_repl()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment