forked from Archives/langchain
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
1.0 KiB
Python
33 lines
1.0 KiB
Python
import pexpect
|
|
|
|
def interact_with_python_shell(child: pexpect.spawn, **kwargs) -> str:
|
|
"""Interact with a Python shell running in a pexpect spawn instance."""
|
|
try:
|
|
child.expect(">>>", **kwargs)
|
|
except pexpect.exceptions.TIMEOUT:
|
|
print("no data")
|
|
return child.before.strip()
|
|
buf = ""
|
|
max_reads=5
|
|
read_cnt=0
|
|
while True:
|
|
if read_cnt > max_reads:
|
|
print("reached max depth")
|
|
break
|
|
try:
|
|
child.expect("\n>>>", **kwargs)
|
|
result = child.before.strip()
|
|
if len(result) > 0:
|
|
buf += result + "\n"
|
|
except pexpect.exceptions.TIMEOUT:
|
|
# The child process is still running, but it's not outputting anything.
|
|
# Wait a bit and try again.
|
|
#TODO: add trial times before exit
|
|
read_cnt += 1
|
|
continue
|
|
except pexpect.exceptions.EOF:
|
|
# The child process has exited.
|
|
print("EOF")
|
|
break
|
|
return buf
|