forked from Archives/langchain
attach to pty with pexpect
parent
c9e6baf60d
commit
9b19eb03aa
@ -0,0 +1,32 @@
|
||||
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
|
Loading…
Reference in New Issue